<?php

namespace control;

/*
*员工档案类
*/

class staffProfilesClass extends adIndexClass
{
	private const page  = 'staffProfiles';
	private const table = 'staff';
	private const title = '员工档案';
	private array $warnOption  = ['10' => '待签合同', '20' => '待参保', '30' => '合同将到期'];
	public array  $stateOption = ['试用', '转正', '留职', '离职'];
	public array  $sexOption   = ['男', '女'];
	
	public function searchHtml(): string
	{
		//生成查询表单
		$option = [];
		for ($i = 1; $i <= 12; $i++) {
			$option[] = sprintf("%02d", $i);
		}
		return
//            checkbox(array(
//				"name"    => "state",
//				"title"   => L('staffProfiles.table.state'),
//				"value"   => $this->stateOption,
//				"checked" => array("试用", '转正', '留职'),
//			)) . space .
		       text(array("name" => "name", "title" => L('staffProfiles.table.name'))) .
//		       selectMultiple(["name" => "departmentId", 'table' => "department", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => L('staffProfiles.table.department')]) .
		       selectMultiple(["name" => "jobId", 'table' => " job", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => L('staffProfiles.table.job')]) .
		       select(array("name" => "sex", "title" => L('staffProfiles.table.sex'), "option" => $this->sexOption)) .
		       text(array("name" => "tel", "title" => L('staffProfiles.table.tel'))) ;
//		       text(array("name" => "idCard", "title" => L('staffProfiles.table.idCard'))) .
//		       select(array("name" => "month", "title" => L('staffProfiles.table.birthDate'), "option" => $option)) .
//		       select(array("name" => "warnTip", "title" => L('staffProfiles.table.warn_message'), "option" => $this->warnOption)) .
//		       select(array("name" => "workFlow", "title" => L('staffProfiles.table.workFlow'), "option" => ['待复核', '已复核'])) .
//		       text(array("name" => "registerDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "入职日期-入职日期"));
	}
	
	/*列表-查询条件*/
	public function home()
	{
		return $this->homeFun($this->search($this->searchHtml()));
	}
	
	/*客户列表-查询结果*/
	public function homeSearch()
	{
		$warnDay = para('workContractWarnDay');
		//like查询数组
		$like = array(
			"st.name"   => $this->post('name'),//姓名
			"st.tel"    => $this->post('tel'),//手机号
			"ta.idCard" => $this->post('idCard'),//身份证号
		);
		//全等查询数组
		$equal = array(
			"st.jobId"    => $this->post('jobId'),//职位
			"ta.sex"      => $this->post('sex'),//性别
			"st.workFlow" => $this->post('workFlow'),
		);
		$and   = "";
		if (!empty($this->post('departmentId'))) {
			//部门
			$and .= " and st.jobId in (select id from job where departmentId = '{$this->post('departmentId')}')";
		}
		if ($this->post('registerDate')) {
			$and .= self::timeComparison($this->post('registerDate'), field: 're.entryDate');
		}
		if (!empty($this->post('state'))) {
			$and .= " and st.state in ('" . implode("','", $this->post('state')) . "') ";
		}
		if (!empty($this->post('month'))) {
			$and .= " and date_format(ta.birthDay,'%m') = '{$this->post('month')}' ";
		}
		if ($this->post('warnTip')) {
			$and .= match ($this->post('warnTip')) {
				'10'    => " and st.stid not in (select staffId from staff_contract where workFlow ='生效中' and isClose = 0) ",
				'20'    => " and st.stid not in (select staffId from staff_insure where workFlow in ('参保中','待停保')) ",
				'30'    => " and st.stid in (select staffId from staff_contract where workFlow = '生效中' and DATEDIFF(signEndDate,DATE_FORMAT(now(),'%Y-%m-%d')) <= '$warnDay' and isClose = 0) ",
				default => ""
			};
		}
		//获取查询结果
		$where                       = search(array("like" => $like, "=" => $equal)) . $and;
		$page                        = $this->page(array(
			'field' => " ta.*,re.entryDate,st.stid,st.jobId as realJobId,st.state,st.orderNo as stNo,st.name,st.manager,st.workFlow",
			"table" => self::table . " as st left join talent_pool as ta on st.talentId = ta.id left join staff_entry_record as re on (re.talentId = st.talentId and re.id not in (select entryId from staff_quit_record where isConfirm = 1))",
			"where" => $where,
			"order" => "re.entryDate desc",
		));
		$_SESSION[self::page]['sql'] = $page['fullSql'];
		//获取表头
		$checkAll = $this->checkAll("listForm", "listId");
		$tr[]     = array($checkAll,
//            L('staffProfiles.table.orderNo'),
            L('staffProfiles.table.name'),
//            L('staffProfiles.table.department'),
            L('staffProfiles.table.job'),
//            L('staffProfiles.table.idCard'),
            L('staffProfiles.table.sex'),
            L('staffProfiles.table.tel'),
//            L('staffProfiles.table.birthDate'),
//            L('staffProfiles.table.entryDate'),
//            L('staffProfiles.table.contractDate'),
//            L('staffProfiles.table.insureDate'),
//            L('staffProfiles.table.endDate'),
//            L('staffProfiles.table.state')
);
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate     = array(
				"box"    => array("name" => "listId", "value" => $array['stid']),
				'edit'   => array("title" => L('staffProfiles.button.edit'), "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=entry&id=" . $array['stid'] . "')"),
				"detail" => array("title" => L('staffProfiles.detail.staff_info'), "click" => "newIframe('" . L('staffProfiles.detail.staff_info') . "','" . $url . "&fun=detail&id=" . $array['stid'] . "')"),
			);
			$job          = query('job', " id = '$array[realJobId]'");
			$contract     = query('staff_contract', "staffId = '$array[stid]'  order by signDate desc");
			$staff_insure = query('staff_insure', "staffId = '$array[stid]'");
			if ($contract['contractLimitType'] == '无固定期限') {
				$contractLimitType = $contract['contractLimitType'];
			} else {
				$contractLimitType = strtotime($contract['signEndDate']) > 0 && strtotime($contract['signEndDate']) < time() ? "<span class='red'>{$contract['signEndDate']}</span>" : self::null($contract['signEndDate']);
			}
			$tr[] = array($this->dominate($dominate),
//                $array['stNo'],
                $array['name'],
//                departmentClass::getTypeName($job['departmentId']),
                $job['name'],
// $array['idCard'],
                $array['sex'],
                $array['tel'],
//                self::null($array['birthDay']),
//                $array['entryDate'],
//                $contract['signDate'],
//                $staff_insure['insureDate'],
//                $contractLimitType,
//                $array['workFlow'] == '待复核' ? $array['workFlow'] : $array['state']
);
		}
		//控件
		$button = "";
		if ($this->power(self::page, "audit")) {
			$button .= "<span class='spanButton' onclick=\"layer('" . self::page . "', 'review', {'act': 'del'})\">" . L('staffProfiles.button.batchReview') . "</span>\n";
		}
		if ($this->power(self::page, "del")) {
			$button .= "<span class='spanButton' onclick=\"layer('" . self::page . "', 'operate', {'act': 'del'})\">" . L('staffProfiles.button.del') . "</span>\n";
		}
		if ($this->power(self::page, "import")) {
			$button .= importTemplateClass::importTemplateButton(self::page) .
			           $this->upButton(array("title" => L('staffProfiles.button.import'), "fun" => "import"));
		}
		if ($this->power(self::page, "export")) {
			$button .= "  <a href='" . root . "control/adIndex.html?cla=" . self::page . "&fun=exportData'><span class='spanButton'>" . L('staffProfiles.button.export') . "</span></a>\n";
		}
		
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}
	
	/**
	 * 复核
	 */
	public function review(): bool|string
	{
		//生成表单
		$html = $this->layerEdit(array(
			"table"      => array(
				array(
					L('staffProfiles.tip.review_key') . "：" => L('staffProfiles.tip.review_title'),
				),
			), 'formTwo' => 'listForm',
		));
		//返回
		return $this->layer(array("title" => L('staffProfiles.button.review'), "height" => 165, "width" => 500, "html" => $html));
	}
	
	/**
	 * 复核
	 */
	public function reviewEdit(): bool|string
	{
		$idArr = $this->post('listId');
		if (static::is_null_array($idArr)) {
			$all = find(array('table' => self::table, 'where' => "worKFlow = '待复核'"));
			foreach ($all['array'] as $array) {
				$idArr[] = $array['stid'];
			}
		}
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = L('staffProfiles.tip.permission_edit_warn');
		} elseif (static::is_null_array($idArr)) {
			$json['warn'] = L('staffProfiles.tip.no_check_data');
		} else {
			$field = [
				'workFlow' => '已复核',
			];
			$x     = 0;
			//存货库存有余额时可以停用
			$warn = '';
			foreach ($idArr as $k => $staffId) {
				$staff = query("staff", " stid = '$staffId' ");
				if ($staff['workFlow'] == '待复核') {
					$json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " stid = '$staffId'"));
					if ($json['warn'] == '更新成功') {
						$x++;
						$warn .= str_replace(['{{staffName}}'], [$staff['name']], L('staffProfiles.other.check_staff_text')) . "<br>";
					} else {
						$warn .= str_replace(['{{staffName}}'], [$staff['name']], L('staffProfiles.other.check_staff_text_failed')) . "<br>";
					}
				}
			}
			//添加日志
			$text = str_replace(['{{staffName}}'], [$this->control['name']], L('staffProfiles.other.check_staff_log'));
			$this->logText(["type" => self::page, "text" => $text]);
			//返回
			$_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('staffProfiles.other.check_staff_msg'));
			$json['warn']     = 2;
		}
		//返回
		return json_encode($json, 320);
	}
	
	/**
	 * 下载模板
	 */
	public function downloadModel()
	{
		if (!$this->power(self::page, 'import')) {
			$_SESSION['warn'] = L('staffProfiles.other.permission_import_warn');
		} else {
//			$title  = [
//				'*' . L('staffProfiles.table.name'),
//                '*' . L('staffProfiles.table.sex'), '*' . L('staffProfiles.table.tel'),
//                '*' . L('staffProfiles.table.idCard'),
//                '*' . L('staffProfiles.table.education'),
//                '*' . L('staffProfiles.table.jobCode'),
//                L('job.table.job_name'),
//                '*' . L('staffProfiles.table.entryDateA'),
//				'*' . L('staffProfiles.table.tryDateA'),
//                '*' . L('staffProfiles.table.workSalary'),
//                L('staffProfiles.table.insureA'),
//                L('staffProfiles.table.contractTypeA'),
//                L('staffProfiles.table.contractyearA'),
//				L('staffProfiles.table.managerName'),
//                L('staffProfiles.table.managerNo'),
//                L('staffProfiles.table.college'),
//                L('staffProfiles.table.email'),
//                L('staffProfiles.table.expect_address'),
//                L('staffProfiles.table.expect_salary'),
//                L('staffProfiles.table.birthDayA'),
//                L('staffProfiles.table.nation'),
//                L('staffProfiles.table.homeTown'),
//				L('staffProfiles.table.height') .'(cm)',
//                L('staffProfiles.table.weight') . '(kg)',
//                L('staffProfiles.table.health'),
//                L('staffProfiles.table.major'),
//                L('staffProfiles.table.jobTitle'),
//                L('staffProfiles.table.workInDate'),
//                L('staffProfiles.table.marriage'),
//                L('staffProfiles.table.politicsStatus'),
//                L('staffProfiles.table.residenceAddress'),
//				L('staffProfiles.other.residenceType'),
//                L('staffProfiles.table.liveAddress'),
//                L('staffProfiles.table.postCode'),
//                L('staffProfiles.table.secContactName'),
//                L('staffProfiles.table.secContactRelation'),
//                L('staffProfiles.table.secContactTel'),
//                L('staffProfiles.table.none_compete'), L('staffProfiles.table.text'), L('staffProfiles.table.work_text'),
//			];
            $title=[
                L('staffProfiles.table.name'),
                L('staffProfiles.table.sex'),
                L('staffProfiles.table.tel'),
                L('staffProfiles.table.job'),
            ];
			$data[] = [
				'张三(示例数据)', '男', '13000000000',  '总经理'];
			$text   = str_replace(['{{staffName}}'], [$this->control['name']], L('staffProfiles.other.staff_import_log'));
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, L('staffProfiles.other.staff_import_temp') . '.xlsx');
			exit(0);
		}
		header("Location:" . getenv("HTTP_REFERER"));
	}
	
	
	/*数据导入分析*/
	public function import()
	{
		if (!$this->power(self::page, 'import')) {
			$_SESSION['warn'] = L('staffProfiles.tip.permission_import_warn');
		} else {
			$talent = new talentPoolClass();
			
			$data               = $this->importHead(format: [
				2 => \Vtiful\Kernel\Excel::TYPE_STRING,
				3 => \Vtiful\Kernel\Excel::TYPE_STRING,
			]);
			$x                  = 0;
			$text               = '';
			$staffEntry         = new staffEntryRecordClass();
			$contractTypeOption = para('contractTypeOption', '，');
			$education          = para('education', '，');
			$nationOption       = para('nationOption', '、');
			$healthOption       = para('healthOption', '，');
			$jobTitleOption     = para('jobTitleOption', '，');
			$politicsStatus     = para('politicsStatus', '，');
			foreach ($data as $i => $row) {
				if ($i > 0) {
					$cell       = formSubArray($row);
//					$cell[7]    = self::importDateFormat($cell[7]);     //入职日期
//					$cell[8]    = self::importDateFormat($cell[8]);     //试用期
//					$cell[19]   = self::importDateFormat($cell[19]);    //出生年月
					$job        = query('job', " name = '$cell[3]'");//工作岗位
//					$manager    = query('staff', "orderNo = '$cell[14]'");
					$manager    = query('staff', "orderNo = ''");
					$field      = [
						'state'              => '已入职',
						'workFlow'           => 2,
						'name'               => $cell[0],
						'sex'                => $cell[1],
						'tel'                => $cell[2],
                        'jobId'              => $job['id'],
//						'idCard'             => $cell[3],
//						'education'          => $cell[4],
//						'college'            => $cell[15],
//						'email'              => $cell[16],
//						'exWorkPlace'        => $cell[17],
//						'exSalary'           => $cell[18],
//						'birthDay'           => $cell[19],
//						'nation'             => $cell[20],
//						'homeTown'           => $cell[21],
						'height'             => $cell[22]??'',
						'weight'             => $cell[23]??'',
//						'health'             => $cell[24],
//						'major'              => $cell[25],
//						'jobTitle'           => $cell[26],
//						'workDate'           => $cell[27],
//						'marriage'           => $cell[28],
//						'politicsStatus'     => $cell[29],
//						'residenceAddress'   => $cell[30],
//						'residenceType'      => $cell[31],
//						'liveAddress'        => $cell[32],
//						'postCode'           => $cell[33],
//						'secContactName'     => $cell[34],
//						'secContactRelation' => $cell[35],
//						'secContactTel'      => $cell[36],
						'isProhibition'      => '无',
//						'text'               => $cell[38],
					];
					$annotation = [
						'name'  => L('staffProfiles.table.name'),
						'sex'   => L('staffProfiles.table.sex'),
						'tel'   => L('staffProfiles.table.tel'),
						'jobId' => L('staffProfiles.table.job'),
					];
					$rules      = [
						'name'  => 'required',
						'sex'   => 'required',
						'tel'   => 'required|tel',
						'jobId' => 'required',
					];
					// 校验是否符合规则
					$vt           = new \verify();
					$result       = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
//					$entryField   = [
//						'jobId'             => $job['id'],
//						'managerId'         => $manager['stid'],
//						'entryDate'         => $cell[7],
//						'endDate'           => $cell[8],
//						'text'              => $cell[39],
//						'contractType'      => '劳动合同',
//						'contractYear'      => $cell[11] == '固定期限' ? $cell[12] : 0,
//						'contractLimitType' => $cell[11] ?: '无固定期限',
//						'workSalary'        => $cell[9],
//						'insure'            => $cell[10] ?: '无',
//					];
					$entryField   = [
						'jobId'             => $job['id'],
						'managerId'         => $manager['stid'],
						'entryDate'         => $cell[7]??'',
						'endDate'           => $cell[8]??'',
						'text'              => $cell[39]??'',
						'contractType'      => '劳动合同',
						'contractYear'      =>  0,
						'contractLimitType' => '无固定期限',
						'workSalary'        => $cell[9]??'',
						'insure'            => $cell[10] ?? '无',
					];
					$enAnnotation = [
						'jobId'             => L('staffProfiles.table.job'),
						'entryDate'         => L('staffProfiles.table.entryDate'),
						'endDate'           => L('staffProfiles.table.tryDate'),
						'contractType'      => L('staffProfiles.table.contractType'),
						'contractLimitType' => L('staffProfiles.table.contractyear'),
						'workSalary'        => L('staffProfiles.table.workSalary'),
						'insure'            => L('staffProfiles.table.insure'),
					];
					$enRules      = [
						'jobId'             => 'required',
//						'entryDate'         => 'required',
//						'endDate'           => 'required',
//						'contractType'      => 'required',
//						'contractLimitType' => 'required',
//						'workSalary'        => 'required',
//						'insure'            => 'required',
					];
					$talentPool   = query('talent_pool', "tel = '$field[tel]'");
					$staff        = query(self::table, "talentId = '$talentPool[id]'");
					// 校验是否符合规则
					$vt2         = new \verify();
					$entryResult = $vt2->setAliases($enAnnotation)->validate($entryField, $enRules)->isOk();
					$line        = str_replace(['{{i}}'], [$i], L('job.other.line'));
					if (empty($job['id'])) {
						$text .= $line . "：" . L('staffProfiles.other.codeToJob') . "<br>";  // 多个规则提示最前面一条
					}elseif ($talentPool['id']){
                        $text.=$line.":".'手机号重复';
                    }
					elseif ($result === false) {
						$text .= $line . "：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
					} elseif ($entryResult === false) {
						$text .= $line . "：" . $vt2->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
					}
//					elseif (empty($field['idCard'])) {//&& (static::total(array('sql' => "SELECT count(*) AS total FROM talent_pool where idCard = '{$field['idCard']}' and id !='$field[id]'"))) > 0
//						$text .= $line . "：" . L('staffProfiles.tip.idCard_repeat_warn') . "<br>";
//					}
					elseif (!empty($field['birthDay']) && strtotime($field['birthDay']) === false) {
						$text .= $line . "：" . L('staffProfiles.other.birthDayError') . "<br>";
					} elseif (!empty($field['birthDay']) && $this->age($field['birthDay']) < 16) {
						$text .= $line . "：" . L('staffProfiles.other.age_warn') . "<br>";
					} elseif (!empty($entryField['contractType']) && !in_array($entryField['contractType'], $contractTypeOption)) {
						$text .= $line . "：" . L('staffProfiles.other.contractType_range') . "<br>";
					} elseif (!empty($entryField['contractLimitType']) && !in_array($entryField['contractLimitType'], workContractClass::contractLimitType)) {
						$text .= $line . "：" . L('staffProfiles.other.contractYear_range') . "<br>";
					} elseif ($entryField['contractLimitType'] == '固定期限' && !is_int($entryField['contractYear'])) {
						$text .= $line . "：" . L('staffProfiles.other.contractYear_limit') . "<br>";
					} elseif ($entryField['contractYear'] > 100) {
						$text .= $line . "：" . L('staffProfiles.other.contractYear_transfinite') . "<br>";
					} elseif (!empty($field['education']) && !in_array($field['education'], $education)) {
						$text .= $line . "：" . L('staffProfiles.other.education_range') . "<br>";
					} elseif (!empty($field['nation']) && !in_array($field['nation'], $nationOption)) {
						$text .= $line . "：" . L('staffProfiles.other.nation_range') . "<br>";
					} elseif (!empty($field['health']) && !in_array($field['health'], $healthOption)) {
						$text .= $line . "：" . L('staffProfiles.other.health_range') . "<br>";
					} elseif (!empty($field['jobTitle']) && !in_array($field['jobTitle'], $jobTitleOption)) {
						$text .= $line . "：" . L('staffProfiles.other.jobTitle_range') . "<br>";
					} elseif (!empty($field['politicsStatus']) && !in_array($field['politicsStatus'], $politicsStatus)) {
						$text .= $line . "：" . L('staffProfiles.other.politicsStatus_range') . "<br>";
					} elseif (!empty($field['residenceType']) && !in_array($field['residenceType'], $talent->residenceTypeOption)) {
						$text .= $line . "：" . L('staffProfiles.other.residenceType_range') . "<br>";
					}
//					elseif (!empty($manager['stid']) && $manager['stid'] == $staff['stid']) {
//						$text .= $line . "：" . L('staffProfiles.other.managerRepeat') . "<br>";
//					}
					else {
						if (empty($talentPool['id'])) {
							$field = array_merge($field, [
								'id' => suiji(),
							]);
							$warn  = static::insert(["table" => 'talent_pool', "field" => $field]);
						} else {
							$warn        = static::update(["table" => 'talent_pool', "field" => $field, 'where' => "id = '$talentPool[id]'"]);
							$field['id'] = $talentPool['id'];
						}
						if (in_array($warn, ["新增成功", "更新成功"])) {
							$entryRecord = query('staff_entry_record', "talentId = '$field[id]' and id not in (select entryId from staff_quit_record where isConfirm = 1)");
							
							if (empty($entryRecord['id'])) {
								//新增入职记录
								$userNo     = codeTemplateClass::generateCode('staffEntryRecord', [
									'prefix' => 'RZSQ' . date('Ymd'),
									'table'  => 'staff_entry_record',
									'field'  => 'orderNo',
									'where'  => '',
								], []);
								$department = query('department', " id = '{$this->controlJob['departmentId']}'");
								$entryField = array_merge($entryField, [
									'id'       => suiji(),
									'orderNo'  => $userNo,
									'deptName' => $department['name'],
									'time'     => $this->time,
									'state'    => '已通过',
									'stid'     => $this->control['stid'],
									'talentId' => $field['id'],
								]);
								$entryWarn  = static::insert(array('table' => 'staff_entry_record', 'field' => $entryField));
							} else {
								$entryField       = array_merge($entryField, [
									'talentId' => $field['id'],
								]);
								$entryWarn        = static::update(array('table' => 'staff_entry_record', 'field' => $entryField, 'where' => "id = '$entryRecord[id]'"));
								$entryField['id'] = $entryRecord['id'];
							}
							if (!in_array($entryWarn, ["新增成功", "更新成功"])) $text .= $line . "：" . $entryWarn . "<br>";
							$staff_entry_record = query('staff_entry_record', "id = '$entryField[id]'");
							//新增员工
							$stid = $staff_entry_record['id'] ? $staffEntry->insertStaff($staff_entry_record, '待复核') : '';
							if ($stid && $staff_entry_record['id']) {
								$x++;
								//生成合同
								$staffEntry->insertContract($stid, $staff_entry_record, '导入');
								//生成社会保险
								$staffEntry->insertInsure($stid, $staff_entry_record, '导入');
								$text .= $line . "：" . L('job.other.import_success') . "<br>";
							} else {
								delete(array('table' => 'talent_pool', 'where' => "id = '$field[id]'"));
								delete(array('table' => 'staff_entry_record', 'where' => "talentId = '$field[id]'"));

								$text .= $line . "：" . L('job.other.import_failed') . "<br>";
							}
						} else {

							$text .= $line . "：" . L('job.other.import_failed') . "<br>";
						}
					}
				}
			}
			$text = str_replace(['{{staffName}}', '{{fileName}}'], [$this->control['name'], $_FILES['file']['name']], L('job.other.import_log')) . '：' . $text;
			$this->logText(["type" => self::page, "text" => $text]);
			$warn             = str_replace(['{{x}}'], [$x], L('job.other.import_warn'));
			$_SESSION['warn'] = $warn;
		}
		header("Location:" . getenv("HTTP_REFERER"));
		exit(0);
	}
	
	/**
	 * 根据生日计算年龄
	 *
	 * @param $birthday
	 * @return false|int|string
	 */
	public function age($birthday)
	{
		$age = strtotime($birthday);
		if ($age === false || $birthday == '0000-00-00' || $birthday == '0100-01-01' || empty($birthday)) {
			return false;
		}
		list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
		$now = strtotime("now");
		list($y2, $m2, $d2) = explode("-", date("Y-m-d", $now));
		$age = $y2 - $y1;
		if ((int)($m2 . $d2) < (int)($m1 . $d1))
			$age -= 1;
		return $age;
	}
	
	/**
	 * 导出
	 */
	public function exportData()
	{
		if (!$this->power(self::page, 'export')) {
			$_SESSION['warn'] = L('staffProfiles.tip.permission_export_warn');
		} else {
			$data            = [];
			$sql             = $_SESSION[self::page]['sql'];
//			$title           = [
//				L('staffProfiles.table.orderNo'), L('staffProfiles.table.name'), L('staffProfiles.table.sex'), L('staffProfiles.table.tel'), L('staffProfiles.table.job'), L('staffProfiles.table.superior'), L('staffProfiles.table.entryDate'), L('staffProfiles.table.tryDate'), L('staffProfiles.table.expect_address'), L('staffProfiles.table.expect_salary'), L('staffProfiles.table.idCard'), L('staffProfiles.table.birthDay'), L('staffProfiles.table.nation'), L('staffProfiles.table.homeTown'), L('staffProfiles.table.email'), L('staffProfiles.table.height') . '(cm)', L('staffProfiles.table.weight') . '(kg)',
//				L('staffProfiles.table.health'), L('staffProfiles.table.education'), L('staffProfiles.table.major'), L('staffProfiles.table.college'), L('staffProfiles.table.workInDate'), L('staffProfiles.table.marriage'), L('staffProfiles.table.politicsStatus'), L('staffProfiles.table.postCode'), L('staffProfiles.table.residenceAddress'), L('staffProfiles.table.residenceType'), L('staffProfiles.table.liveAddress'), L('staffProfiles.table.secContactName'), L('staffProfiles.table.secContactRelation'), L('staffProfiles.table.secContactTel'), L('staffProfiles.table.isProhibition'), L('staffProfiles.table.text'),
//			];
            $title=[
                L('staffProfiles.table.name'),
                L('staffProfiles.table.sex'),
                L('staffProfiles.table.tel'),
                L('staffProfiles.table.job'),
            ];

			$result['array'] = sqlFind($sql);
			if (is_array($result['array'])) {
				foreach ($result['array'] as $array) {
					$realJob     = query("job", " id = '$array[realJobId]' ");
					$entryRecord = query('staff_entry_record', " talentId = '$array[id]' order by time desc");
					$manager     = query("staff", " stid = '$array[manager]'");
//					$data[]      = [
//						$array['stNo'], $array['name'], $array['sex'], $array['tel'], $realJob['name'], $manager['name'], $entryRecord['entryDate'], $entryRecord['endDate'], $array['exWorkPlace'],
//						$array['exSalary'], $array['idCard'],
//						$array['birthDay'], $array['nation'], $array['homeTown'], $array['email'], $array['height'], $array['weight'], $array['health'], $array['education'],
//						$array['major'], $array['college'], $array['workDate'], $array['marriage'], $array['politicsStatus'], $array['postCode'], $array['residenceAddress'], $array['residenceType'], $array['liveAddress'],
//						$array['secContactName'], $array['secContactRelation'], $array['secContactTel'], $array['isProhibition'], $array['text'],
//					];
					$data[]      = [
					 $array['name'], $array['sex'], $array['tel'], $realJob['name']];
				}
			}
			$text = str_replace(['{{staffName}}'], [$this->control['name']], L('staffProfiles.other.export_log'));
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, L('staffProfiles.table.staffForm') . ".xlsx");
		}
		header("Location:" . getenv("HTTP_REFERER"));
		exit(0);
	}
	
	
	/**
	 * 入职页
	 *
	 * @return string
	 */
	public function entry(): string
	{
		$staff = query(self::table, " stid = '" . $this->get('id') . "' ");
		$info  = query('talent_pool', " id = '" . $staff['talentId'] . "' ");
		
		/*****学习经历*********/
		$educationTr[] = [
			L('staffProfiles.table.study_date'),
			L('staffProfiles.table.university'),
			L('staffProfiles.table.study_major'),
			L('staffProfiles.table.achievements'),
			L('staffProfiles.table.operation'),
		];
		$result        = find(array('table' => "study_history where talentId = '{$info['id']}' order by list asc"));
		
		foreach ($result['array'] as $array) {
			$educationTr[] = [
				hidden(array('name' => 'studyId[]', 'value' => $array['id'])) .
				text(array('name' => 'educationDate[]', 'value' => $array['studyDate'], 'laydate' => ['range' => '~'])),
				text(array('name' => 'school[]', 'value' => $array['college'])),
				text(array('name' => 'schoolMajor[]', 'value' => $array['major'])),
				text(array('name' => 'certificate[]', 'value' => $array['certificate'])),
				"<span class='del-row-button' onclick='decline(this)'>" . L('staffProfiles.button.del') . "</span>",
			];
		}
		
		/*****工作经历*********/
		$workTr[] = [
			L('staffProfiles.table.work_date_start'),
			L('staffProfiles.table.employed'),
			L('staffProfiles.table.station'),
			L('staffProfiles.table.work_content'),
			L('staffProfiles.table.quit_reason'),
			L('staffProfiles.table.operation'),
		];
		$result   = find(array('table' => "job_history where talentId = '{$info['id']}' order by list asc"));
		foreach ($result['array'] as $array) {
			$workTr[] = [
				hidden(array('name' => 'workId[]', 'value' => $array['id'])) .
				text(array('name' => 'workDate[]', 'value' => $array['workDate'], 'laydate' => ['range' => '~'])),
				text(array('name' => 'companyName[]', 'value' => $array['companyName'])),
				text(array('name' => 'position[]', 'value' => $array['position'])),
				text(array('name' => 'content[]', 'value' => $array['content'])),
				text(array('name' => 'cause[]', 'value' => $array['cause'])),
				"<span class='del-row-button' onclick='decline(this)'>" . L('staffProfiles.button.del') . "</span>",
			];
		}
		
		/*****家庭成员*********/
		$familyTr[] = [
			L('staffProfiles.table.name'),
			L('staffProfiles.table.relationship'),
			L('staffProfiles.table.work_unit'),
			L('staffProfiles.table.contactTel'),
			L('staffProfiles.table.operation'),
		];
		$result     = find(array('table' => "talent_family where talentId = '{$info['id']}' order by list asc"));
		foreach ($result['array'] as $array) {
			$familyTr[] = [
				hidden(array('name' => 'familyId[]', 'value' => $array['id'])) .
				text(array('name' => 'memberName[]', 'value' => $array['name'])),
				text(array('name' => 'relation[]', 'value' => $array['relation'])),
				text(array('name' => 'memberCompany[]', 'value' => $array['company'])),
				text(array('name' => 'contactTel[]', 'value' => $array['contactTel'])),
				"<span class='del-row-button' onclick='decline(this)'>" . L('staffProfiles.button.del') . "</span>",
			];
		}
		//引入人才库对象
		$talentObj = new talentPoolClass();
		$button    = $photo = [];
		if ($this->power(self::page, "edit")) {
			//按钮
			$button[] = [
				"name"  => L('public.save'),
				"type"  => "点击事件",
				"cla"   => $this->get('cla'),
				"fun"   => "subForm('" . self::page . "EntryForm', root+'control/adIndex.html?cla=" . self::page . "&fun=entryEdit')",
				"post"  => ["id" => $this->get('id')],
				'style' => 'li-btn-blue-bg',
			];
			$button[] = [
				"name"  => L('public.saveDraft'),
				"type"  => "点击事件",
				"cla"   => $this->get('cla'),
				"fun"   => "saveTemp('" . self::page . "', 'entry', '" . self::page . "EntryForm')",
				"post"  => ["id" => $this->get('id')],
				'style' => 'li-btn-green-bg',
			];
			
			$ico = [];
			$all = find(array('table' => 'file', 'where' => "targetId = '$info[id]' and target in ('入职登记表','身份证正面','身份证背面','毕业证','学位证','银行卡','离职证明','体检报告','职称证书','竞业限制协议')"));
			foreach ($all['array'] as $array) {
				$ico[$array['target']] = ['id' => $array['id'], 'src' => $array['src']];
			}
			$photo = array(
				array("title" => L('staffProfiles.table.front_of_id_card'), 'type' => '身份证正面', "url" => $ico['身份证正面']['src'] ?? '', "fileId" => $ico['身份证正面']['id'] ?? '', "id" => $info['id']),
				array("title" => L('staffProfiles.table.back_of_id_card'), 'type' => '身份证背面', "url" => $ico['身份证背面']['src'] ?? '', "fileId" => $ico['身份证背面']['id'] ?? '', "id" => $info['id']),
				array("title" => L('staffProfiles.table.diploma'), 'type' => '毕业证', "url" => $ico['毕业证']['src'] ?? '', "fileId" => $ico['毕业证']['id'] ?? '', "id" => $info['id']),
				array("title" => L('staffProfiles.table.degree_diploma'), 'type' => '学位证', "url" => $ico['学位证']['src'] ?? '', "fileId" => $ico['学位证']['id'] ?? '', "id" => $info['id']),
				array("title" => L('staffProfiles.table.bank_card'), 'type' => '银行卡', "url" => $ico['银行卡']['src'] ?? '', "fileId" => $ico['银行卡']['id'] ?? '', "id" => $info['id']),
				array("title" => L('staffProfiles.table.registration_form'), 'type' => '入职登记表', "url" => $ico['入职登记表']['src'] ?? '', "fileId" => $ico['入职登记表']['id'] ?? '', "id" => $info['id']),
				array("title" => L('staffProfiles.table.leaving_certificate'), 'type' => '离职证明', "url" => $ico['离职证明']['src'] ?? '', "fileId" => $ico['离职证明']['id'] ?? '', "id" => $info['id']),
				array("title" => L('staffProfiles.table.medical_report'), 'type' => '体检报告', "url" => $ico['体检报告']['src'] ?? '', "fileId" => $ico['体检报告']['id'] ?? '', "id" => $info['id']),
				array("title" => L('staffProfiles.table.Professional_certificate'), 'type' => '职称证书', "url" => $ico['职称证书']['src'] ?? '', "fileId" => $ico['职称证书']['id'] ?? '', "id" => $info['id']),
				array("title" => L('staffProfiles.table.competition_agreement'), 'type' => '竞业限制协议', "url" => $ico['竞业限制协议']['src'] ?? '', "fileId" => $ico['竞业限制协议']['id'] ?? '', "id" => $info['id']),
			);
		}
		
		//表单
		$data['html'] = $this->layerEdit([
			"table"  => [
				[
					$this->tableShowButton($button),
				],
				[
					must . L('staffProfiles.table.name') . "：" => text(["name" => "name", "value" => $info['name']]),
					must . L('staffProfiles.table.sex') . "："  => radio(["name" => "sex", 'value' => $this->sexOption, "checked" => $info['sex']]),
				],
				[
					must . L('staffProfiles.table.tel') . "："    => text(["name" => "tel", "value" => $info['tel']]),
					must . L('staffProfiles.table.idCard') . "：" => text(["name" => "idCard", 'blur' => 'getBirthDay', "value" => $info['idCard']]),
				],
				[
					must . L('staffProfiles.table.education') . "：" => select(array('name' => 'education', 'title' => L('staffProfiles.table.education'), 'class' => 'select', 'value' => $info['education'], 'option' => para('education', '，'))),
					L('staffProfiles.table.superior') . "："         => selectMultiple(array('name' => 'manager', 'title' => L('staffProfiles.table.superior'), 'value' => $staff['manager'], 'table' => 'staff', 'sqlId' => 'stid', 'sqlField' => 'name', 'where' => "workFlow='已复核' and state !='离职' order by orderNo asc")),
				],
				[
					L('staffProfiles.table.birthDay') . "：" => text(["name" => "birthDay", 'laydate' => [], "value" => $info['birthDay']]),
					L('staffProfiles.table.email') . "："    => text(["name" => "email", "value" => $info['email']]),
				],
				[
					L('staffProfiles.table.nation') . "："   => select(array('name' => 'nation', 'title' => L('staffProfiles.table.nation'), 'class' => 'select', 'value' => $info['nation'], 'option' => para('nationOption', '、'))),
					L('staffProfiles.table.homeTown') . "：" => repeatSelect(array('name' => 'homeTown', 'title' => L('staffProfiles.table.homeTown'), 'sqlForm' => 'region', 'sqlField' => 'province', 'value' => $info['homeTown'])),
				],
				[
					L('staffProfiles.table.height') . "：" => text(["name" => "height", 'unit' => 'cm', "value" => $info['height'] > 0 ? $info['height'] : '']),
					L('staffProfiles.table.weight') . "：" => text(["name" => "weight", 'unit' => 'kg', "value" => $info['weight'] > 0 ? $info['weight'] : '']),
				],
				[
					L('staffProfiles.table.health') . "：" => select(array('name' => 'health', 'title' => L('staffProfiles.table.health'), 'class' => 'select', 'value' => $info['health'], 'option' => explode('，', para('healthOption')))),
				],
				[
					L('staffProfiles.table.college') . "：" => text(["name" => "college", "value" => $info['college']]),
					L('staffProfiles.table.major') . "："   => text(["name" => "major", "value" => $info['major']]),
				],
				[
					L('staffProfiles.table.workInDate') . "：" => text(["name" => "workInDate", "value" => $info['workDate']]),
					L('staffProfiles.table.jobTitle') . '：'   => select(array('name' => 'jobTitle', 'title' => L('staffProfiles.table.choose'), 'class' => 'select', 'value' => $info['jobTitle'], 'option' => explode('，', para('jobTitleOption')))),
				],
				[
					L('staffProfiles.table.marriage') . "："       => radio(["name" => "marriage", 'value' => $talentObj->marryOption, "checked" => $info['marriage']]),
					L('staffProfiles.table.politicsStatus') . "：" => select(array('name' => 'politicsStatus', 'title' => L('staffProfiles.table.politicsStatus'), 'class' => 'select', 'value' => $info['politicsStatus'], 'option' => explode('，', para('politicsStatus')))),
				],
				[
					L('staffProfiles.table.residenceAddress') . "：" => text(["name" => "residenceAddress", "value" => $info['residenceAddress']]),
					L('staffProfiles.table.residenceType') . "："    => radio(["name" => "residenceType", 'value' => $talentObj->residenceTypeOption, "checked" => $info['residenceType']]),
				],
				[
					L('staffProfiles.table.liveAddress') . "：" => text(["name" => "liveAddress", "value" => $info['liveAddress']]),
					L('staffProfiles.table.postCode') . "："    => text(["name" => "postCode", "value" => $info['postCode']]),
				
				],
				[
					L('staffProfiles.table.secContactName') . "："     => text(["name" => "secContactName", "value" => $info['secContactName']]),
					L('staffProfiles.table.secContactRelation') . "：" => text(["name" => "secContactRelation", "value" => $info['secContactRelation']]),
				
				],
				[
					L('staffProfiles.table.secContactTel') . "：" => text(["name" => "secContactTel", "value" => $info['secContactTel']]),
					L('staffProfiles.table.isProhibition') . "：" => radio(["name" => "isProhibition", 'value' => ['无', '有'], "checked" => $info['isProhibition'] ?: '无']),
				],
				
				[
					L('staffProfiles.table.text') . "：" => textarea(["name" => "text", "value" => $info['text']]),
				],
				[
					"<span class='small-title'>" . L('staffProfiles.table.learning_experience') . "</span>",
				],
				[
					$this->tableMany(array('tr' => $educationTr, 'method' => "addRow(this,'education')", 'end' => true, 'button' => true)),
				],
				[
					"<span class='small-title'>" . L('staffProfiles.table.work_experience') . "</span>",
				],
				[
					$this->tableMany(array('tr' => $workTr, 'end' => true, 'method' => "addRow(this,'work')", 'button' => true)),
				],
				[
					"<span class='small-title'>" . L('staffProfiles.table.family_member') . "</span>",
				],
				[
					$this->tableMany(array('tr' => $familyTr, 'end' => true, 'method' => "addRow(this,'family')", 'button' => true)),
				],
				[
					"<span class='small-title'>" . L('staffProfiles.table.enclosure') . "</span>",
				],
				[
					fileUploadClass::addFileComponent($info['id'], '人才库', self::page, self::page . 'EntryForm'),
				],
				[
					"<div><span class='small-title'>" . L('staffProfiles.table.entry_data') . "</span></div>",
				],
				[
					$talentObj->photo($photo),
				],
			],
			'hidden' => hidden(array('name' => 'id', 'value' => $info['id'])) . "<div class='hidden'><input name=\"type\" type=\"hidden\" ><input name='imgFile' accept=\"image/*\" id='imgFile' type='file' onchange=\"uploadImgFile('{$this->get('cla')}EntryForm',root+'control/adIndex.html?cla=talentPool&fun=uploadIco')\"></div>",
			'button' => ' ',
		]);
		$data['html'] .= $talentObj->editJs();
		//返回
		return $this->tab($data);
	}
	
	
	/**
	 *入职信息保存
	 */
	public function entryEdit()
	{
		$id         = $this->post('id');
		$staff      = query('staff', " talentId = '$id'");
		$field      = [
			'email'              => $this->post('email'),
			'name'               => $this->post('name'),
			'sex'                => $this->post('sex'),
			'tel'                => $this->post('tel'),
			'idCard'             => $this->post('idCard'),
			'birthDay'           => $this->post('birthDay'),
			'nation'             => $this->post('nation'),
			'homeTown'           => $this->post('homeTown'),
			'height'             => $this->post('height'),
			'weight'             => $this->post('weight'),
			'health'             => $this->post('health'),
			'education'          => $this->post('education'),
			'major'              => $this->post('major'),
			'college'            => $this->post('college'),
			'workDate'           => $this->post('workInDate'),
			'marriage'           => $this->post('marriage'),
			'politicsStatus'     => $this->post('politicsStatus'),
			'residenceAddress'   => $this->post('residenceAddress'),
			'residenceType'      => $this->post('residenceType'),
			'liveAddress'        => $this->post('liveAddress'),
			'secContactName'     => $this->post('secContactName'),
			'secContactTel'      => $this->post('secContactTel'),
			'secContactRelation' => $this->post('secContactRelation'),
			'jobTitle'           => $this->post('jobTitle'),
			'text'               => $this->post('text'),
			'isProhibition'      => $this->post('isProhibition'),
			'postCode'           => $this->post('postCode'),
		];
		$annotation = [
			'name'      => L('staffProfiles.table.name'),
			'sex'       => L('staffProfiles.table.sex'),
			'tel'       => L('staffProfiles.table.tel'),
			'idCard'    => L('staffProfiles.table.idCard'),
			'education' => L('staffProfiles.table.education'),
		];
		$rules      = [
			'name'      => 'required',
			'sex'       => 'required',
			'tel'       => 'required|tel',
			'idCard'    => 'required|id_card',
			'education' => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		
		//学习经历
		$studyIdArr       = $this->post('studyId') ?? [];
		$educationDateArr = $this->post('educationDate');
		$schoolArr        = $this->post('school');
		$schoolMajorArr   = $this->post('schoolMajor');
		$certificateArr   = $this->post('certificate');
		//工作经历
		$workIdArr      = $this->post('workId') ?? [];
		$workDateArr    = $this->post('workDate');
		$companyNameArr = $this->post('companyName');
		$positionArr    = $this->post('position');
		$contentArr     = $this->post('content');
		$causeArr       = $this->post('cause');
		//家庭成员
		$familyIdArr      = $this->post('familyId') ?? [];
		$memberNameArr    = $this->post('memberName');
		$relationArr      = $this->post('relation');
		$memberCompanyArr = $this->post('memberCompany');
		$contactTelArr    = $this->post('contactTel');
		//附件
		$fileIdArr = $this->post('fileId');
		
		$where = " id = '$id' ";
		$info  = query('talent_pool', $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = L('staffProfiles.tip.permission_edit_warn');
		} elseif (!preg_match("/^([\x{4e00}-\x{9fa5}]+)$/u", $field['name']) && !preg_match("/^[a-z]+$/i", $field['name'])) {
			$json['warn'] = L('staffProfiles.tip.name_warn');
		} elseif (!empty($field['email']) && preg_match(checkEmail, $field['email']) == 0) {
			$json['warn'] = L('staffProfiles.tip.email_warn');
		} elseif (!empty($field['idCard']) && (static::total(array('sql' => "SELECT count(*) AS total FROM talent_pool where idCard = '{$field['idCard']}' and id !='$id'")))) {
			$json['warn'] = L('staffProfiles.tip.idCard_repeat_warn');
		} elseif (!$info['id']) {
			$json['warn'] = L('staffProfiles.tip.find_none_staff');
		} elseif (!empty($field['birthDay']) && $this->age($field['birthDay']) < 16) {
			$json['warn'] = L('staffProfiles.tip.age_warn');
		} elseif (!empty($this->post('manager')) && $this->post('manager') == $staff['stid']) {
			$json['warn'] = L('staffProfiles.tip.manager_warn');
		} else {
			$this->startTrans();                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              //开启事务
			$isPass       = true;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             //事务通过标志
			$json['warn'] = static::update([
				"table" => 'talent_pool',
				"field" => $field,
				"where" => $where,
			]);
			/******工作信息*******/
			$entryRecord = query('staff_entry_record', " talentId = '$info[id]'  order by time desc");
			if (empty($entryRecord['id'])) {
				//针对管理员  如果没有入职记录 则生成一条
				$userNo     = codeTemplateClass::generateCode('staffEntryRecord', [
					'prefix' => 'RZSQ' . date('Ymd'),
					'table'  => 'staff_entry_record',
					'field'  => 'orderNo',
					'where'  => '',
				], []);
				$department = query('department', " id = '{$this->controlJob['departmentId']}'");
				$entryField = [
					'jobId'             => $staff['jobId'],
					'contractType'      => '劳动合同',
					'contractLimitType' => '无固定期限',
					'entryDate'         => $this->date,
					'endDate'           => $this->date,
					'id'                => self::getId(),
					'state'             => '已通过',
					'orderNo'           => $userNo,
					'stid'              => $this->control['stid'],
					'deptName'          => $department['name'],
					'talentId'          => $info['id'],
				];
				$warn       = static::insert(array('table' => 'staff_entry_record', 'field' => $entryField));
				if (!in_array($warn, ['新增成功', '更新成功'])) {
					$json['warn'] = L('staffProfiles.tip.entry_record_failed');
				}
			}
			
			
			//添加或更新学习经历
			if (is_array($studyIdArr)) {
				foreach ($studyIdArr as $k => $nid) {
					if (static::total(array('table' => 'study_history', 'where' => " and id = '$nid'")) > 0) {
						//更新
						$warn = static::update([
							"table" => 'study_history',
							"field" => [
								'studyDate'   => $educationDateArr[$k],
								'college'     => $schoolArr[$k],
								'major'       => $schoolMajorArr[$k],
								'certificate' => $certificateArr[$k],
							],
							"where" => " id = '$nid'",
						]);
					} else {
						//新增
						$warn = static::insert([
							"table" => 'study_history',
							"field" => [
								'id'          => $nid,
								'talentId'    => $id,
								'studyDate'   => $educationDateArr[$k],
								'college'     => $schoolArr[$k],
								'major'       => $schoolMajorArr[$k],
								'certificate' => $certificateArr[$k],
								'time'        => $this->time,
							],
						]);
					}
					if (!in_array($warn, ['新增成功', '更新成功'])) {
						$isPass       = false;
						$json['warn'] = $warn;
						break;
					}
				}
			}
			
			//添加或更新工作经历
			if (is_array($workIdArr)) {
				foreach ($workIdArr as $k => $nid) {
					if (static::total(array('table' => 'job_history', 'where' => " and id = '$nid'")) > 0) {
						//更新
						$warn = static::update([
							"table" => 'job_history',
							"field" => [
								'companyName' => $companyNameArr[$k],
								'position'    => $positionArr[$k],
								'content'     => $contentArr[$k],
								'cause'       => $causeArr[$k],
								'workDate'    => $workDateArr[$k],
							],
							"where" => " id = '$nid'",
						]);
					} else {
						//新增
						$warn = static::insert([
							"table" => 'job_history',
							"field" => [
								'id'          => $nid,
								'talentId'    => $id,
								'companyName' => $companyNameArr[$k],
								'position'    => $positionArr[$k],
								'content'     => $contentArr[$k],
								'cause'       => $causeArr[$k],
								'workDate'    => $workDateArr[$k],
								'time'        => $this->time,
							],
						]);
					}
					if (!in_array($warn, ['新增成功', '更新成功'])) {
						$isPass       = false;
						$json['warn'] = $warn;
						break;
					}
				}
			}
			
			//添加或更新家庭成员
			if (is_array($familyIdArr)) {
				foreach ($familyIdArr as $k => $nid) {
					if (static::total(array('table' => 'talent_family', 'where' => " and id = '$nid'")) > 0) {
						//更新
						$warn = static::update([
							"table" => 'talent_family',
							"field" => [
								'name'       => $memberNameArr[$k],
								'relation'   => $relationArr[$k],
								'company'    => $memberCompanyArr[$k],
								'contactTel' => $contactTelArr[$k],
							],
							"where" => " id = '$nid'",
						]);
					} else {
						//新增
						$warn = static::insert([
							"table" => 'talent_family',
							"field" => [
								'id'         => $nid,
								'talentId'   => $id,
								'name'       => $memberNameArr[$k],
								'relation'   => $relationArr[$k],
								'company'    => $memberCompanyArr[$k],
								'contactTel' => $contactTelArr[$k],
								'time'       => $this->time,
							],
						]);
					}
					if (!in_array($warn, ['新增成功', '更新成功'])) {
						$isPass       = false;
						$json['warn'] = $warn;
						break;
					}
				}
			}
			
			//添加主表ID到附件表
			if (is_array($fileIdArr)) {
				$warn = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
				if ($warn != '更新成功') {
					$json['warn'] = $warn;
					$isPass       = false;
				}
			}
			$warn = update(array('table' => 'staff', 'field' => ['name' => $field['name'], 'manager' => $this->post('manager'), 'subjectId' => $this->post('subjectId'), 'tel' => $field['tel']], 'where' => " stid = '$staff[stid]'"));
			if ($warn != '更新成功') {
				$json['warn'] = $warn;
				$isPass       = false;
			}
			//更新账号表的姓名和电话
			$warn = update(array('table' => 'user', 'field' => ['name' => $field['name'], 'tel' => $field['tel']], 'where' => " stid = '$staff[stid]'"));
			if ($warn != '更新成功') {
				$json['warn'] = L('staffProfiles.tip.user_warn');
			}
			
			if ($isPass && in_array($json['warn'], ["新增成功", "更新成功"])) {
				$this->commitTrans();//提交事务
				//删除不在此ID中的数据
				delete(array('table' => 'talent_family', 'where' => " id not in ('" . implode("','", $familyIdArr) . "') and talentId = '$staff[talentId]'"));
				delete(array('table' => 'job_history', 'where' => " id not in ('" . implode("','", $workIdArr) . "') and talentId = '$staff[talentId]'"));
				delete(array('table' => 'study_history', 'where' => " id not in ('" . implode("','", $studyIdArr) . "') and talentId = '$staff[talentId]'"));
				//添加日志
				$text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $field['name'], $staff['stid']], L('staffProfiles.other.staff_edit_text'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $staff['stid'];
			} else {
				$this->rollback();//回滚
			}
		}
		resp:
		return json_encode($json, 320);
	}
	
	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " stid = '{$this->get('id')}'");
		if (empty($info['stid'])) {
			$html = L('staffProfiles.detail.find_none_staff');
		} else {
			$talentObj = new talentPoolClass();
			//人才库信息
			$talent = query('talent_pool', " id = '$info[talentId]'");
			//工作信息
			$entry = query('staff_entry_record', " talentId = '$info[talentId]' order by time desc");
			//转正记录
			$staffFormal = query('staff_formal', " talentId = '$info[talentId]' order by time desc");
			//离职记录
			$staffQuit = query('staff_quit_record', " staffId = '$info[stid]' order by time desc");
			//菜单
			$data   = array(
				"id"   => $info['stid'],
				'menu' => [
					"detail"        => L('staffProfiles.detail.base'),
					"studyHistory"  => array("name" => L('staffProfiles.detail.social_resume'), "cla" => "talentPool", "fun" => "studyHistory"),
					'evaluation'    => L('staffProfiles.detail.evaluation'),
					"record"        => L('staffProfiles.detail.change_record'),
					"trainRecord"   => array("name" => L('staffProfiles.detail.train_record'), "cla" => "trainingRecord", "fun" => "trainRecord"),
					"achievements"  => array("name" => L('staffProfiles.detail.performance_record'), "cla" => "performanceScore", "fun" => "achievements"),
					"clockRecord"   => array("name" => L('staffProfiles.detail.attendance_record'), "cla" => "workSign", "fun" => "clockRecord"),
					"salaryRecord"  => array("name" => L('staffProfiles.detail.salary_record'), "cla" => "paySlip", "fun" => "salaryRecord"),
					"rewardsRecord" => array("name" => L('staffProfiles.detail.reward_record'), "cla" => "rewards", "fun" => "rewardsRecord"),
					"asset"         => L('staffProfiles.detail.asset_pick'),
					"setting"       => L('staffProfiles.detail.staff_setting'),
				
				],
			);
			$button = [];
			if ($this->power(self::page, "edit")) {
				//按钮
				$button[] = [
					"name"  => L('staffProfiles.detail.edit'),
					"type"  => "顶部页卡",
					"title" => L('staffProfiles.detail.edit'),
					"url"   => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=entry&id=' . $info['stid'],
					'style' => 'li-btn-blue-bg',
				];
			}
			if ($this->power(self::page, 'del')) {
				//按钮
				$button[] = [
					"name" => L('staffProfiles.button.del'),
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['stid']],
				];
			}
			
			if ($info['state'] == '留职') {
				//按钮
				$button[] = [
					"name" => L('staffProfiles.detail.duty'),
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'recover', "id" => $info['stid']],
				];
			}
			
			$ico = [];
			$all = find(array('table' => 'file', 'where' => "targetId = '$talent[id]' and target in ('入职登记表','身份证正面','身份证背面','毕业证','学位证','银行卡','离职证明','体检报告','职称证书','竞业限制协议')"));
			foreach ($all['array'] as $array) {
				$ico[$array['target']] = $array['src'];
			}
			$photo = array(
				array("title" => L('staffProfiles.table.front_of_id_card'), 'type' => '身份证正面', "url" => $ico['身份证正面'] ?? ''),
				array("title" => L('staffProfiles.table.back_of_id_card'), 'type' => '身份证背面', "url" => $ico['身份证背面'] ?? ''),
				array("title" => L('staffProfiles.table.diploma'), 'type' => '毕业证', "url" => $ico['毕业证'] ?? ''),
				array("title" => L('staffProfiles.table.degree_diploma'), 'type' => '学位证', "url" => $ico['学位证'] ?? ''),
				array("title" => L('staffProfiles.table.bank_card'), 'type' => '银行卡', "url" => $ico['银行卡'] ?? ''),
				array("title" => L('staffProfiles.table.registration_form'), 'type' => '入职登记表', "url" => $ico['入职登记表'] ?? ''),
				array("title" => L('staffProfiles.table.leaving_certificate'), 'type' => '离职证明', "url" => $ico['离职证明'] ?? ''),
				array("title" => L('staffProfiles.table.medical_report'), 'type' => '体检报告', "url" => $ico['体检报告'] ?? ''),
				array("title" => L('staffProfiles.table.Professional_certificate'), 'type' => '职称证书', "url" => $ico['职称证书'] ?? ''),
				array("title" => L('staffProfiles.table.competition_agreement'), 'type' => '竞业限制协议', "url" => $ico['竞业限制协议'] ?? ''),
			);
			/*******附件****************/
			$fileCollection = fileUploadClass::showFile($talent['id'], '人才库');
			//职位
			$job = query('job', " id = '$info[jobId]'");
			//合同信息
			$staffContract = query('staff_contract', " staffId = '$info[stid]' order by signDate desc,time desc");
			//社会保险
			$staffInsure = query('staff_insure', "staffId = '$info[stid]' order by insureDate desc,time desc");
			//生成表单
			$data['html'] = $this->tableShow(array(
				"button"                                => $button,
				array(
					array(
						L('staffProfiles.table.name') => $info['name'],
						L('staffProfiles.table.sex')  => $talent['sex'],
						L('staffProfiles.table.tel')  => $info['tel'],
					),
					array(
						L('staffProfiles.table.email')    => $talent['email'],
						L('staffProfiles.table.idCard')   => $talent['idCard'],
						L('staffProfiles.table.birthDay') => $talent['birthDay'],
					),
					array(
						L('staffProfiles.table.age')      => $this->age($talent['birthDay']),
						L('staffProfiles.table.nation')   => $talent['nation'],
						L('staffProfiles.table.homeTown') => $talent['homeTown'],
					),
				),
				L('staffProfiles.detail.info')          => array(
					array(
						L('staffProfiles.table.education') => $talent['education'],
						L('staffProfiles.table.major')     => $talent['major'],
						L('staffProfiles.table.college')   => $talent['college'],
					),
					array(
						L('staffProfiles.table.workInDate') => $talent['workDate'],
						L('staffProfiles.table.jobTitle')   => $talent['jobTitle'],
					),
					array(
						L('staffProfiles.table.marriage')       => $talent['marriage'],
						L('staffProfiles.table.politicsStatus') => $talent['marriage'],
					),
					array(
						L('staffProfiles.table.height') => $talent['height'] . 'cm',
						L('staffProfiles.table.weight') => $talent['weight'] . 'kg',
						L('staffProfiles.table.health') => $talent['health'],
					),
					
					array(
						L('staffProfiles.table.residenceAddress') => $talent['residenceAddress'],
						L('staffProfiles.table.residenceType')    => $talent['residenceType'],
					),
					array(
						L('staffProfiles.table.liveAddress') => $talent['liveAddress'],
						L('staffProfiles.table.postCode')    => $talent['postCode'],
					),
					array(
						L('staffProfiles.table.secContactName')     => $talent['secContactName'],
						L('staffProfiles.table.secContactRelation') => $talent['secContactRelation'],
						L('staffProfiles.table.secContactTel')      => $talent['secContactTel'],
					),
					array(
						L('staffProfiles.table.text') => $talent['text'],
					),
				),
				L('staffProfiles.detail.work_info')     => array(
					array(
						L('staffProfiles.table.department') => departmentClass::getTypeName($job['departmentId']),
						L('staffProfiles.table.job')        => $job['name'],
						L('job.table.jobType')              => $job['type'],
					),
					array(
						L('staffProfiles.table.superior') => self::findStaff($info['manager']),
					),
					array(
						L('staffProfiles.table.entryDate')  => $entry['entryDate'],
						L('staffProfiles.table.tryDate')    => $entry['endDate'],
						L('staffProfiles.table.formalDate') => $staffFormal['confirmDate'],
					),
					array(
						L('staffProfiles.table.contractType') => $staffContract['contractType'],
						L('staffProfiles.table.contractyear') => $staffContract['contractLimitType'] == '无固定期限' ? $staffContract['contractLimitType'] : $staffContract['contractLimitType'] . '-' . $staffContract['contractYear'] . '个月',
						L('staffProfiles.table.workSalary')   => $staffContract['workSalary'],
					),
					array(
						L('staffProfiles.table.contractDate')        => self::null($staffContract['signDate']),
						L('staffProfiles.table.contractStartAndEnd') => self::null($staffContract['signStartDate']) . '至' . self::null($staffContract['signEndDate']),
						L('staffProfiles.table.contractDismiss')     => self::null($staffContract['stopDate']),
					),
					array(
						L('staffProfiles.table.insure')     => $staffContract['insure'],
						L('staffProfiles.table.insureDate') => self::null($staffInsure['insureDate']),
						L('staffProfiles.detail.insureNo')  => $staffInsure['insureNo'],
					),
					array(
						L('staffProfiles.detail.insure_state') => $staffInsure['workFlow'],
						L('staffProfiles.table.work_text')     => $entry['text'],
					),
				),
				L('staffProfiles.detail.work_contract') => array(
					array(
						fileUploadClass::showFile($staffContract['id']),
					),
				),
				L('staffProfiles.detail.system_info')   => array(
					array(
						L('staffProfiles.table.orderNo') => $info['orderNo'],
						L('staffProfiles.table.state')   => $info['state'],
						L('staffProfiles.table.quitDay') => self::null($staffQuit['confirmDate']),
					),
					array(
						L('staffProfiles.detail.creator')    => self::findStaff($info['stid']),
						L('staffProfiles.detail.creatTime')  => $info['time'],
						L('staffProfiles.detail.updateTime') => $info['updateTime'],
					),
				),
				L('staffProfiles.table.entry_data')     => array(
					array(
						$talentObj->photo($photo),
					),
				),
				L('staffProfiles.table.enclosure')      => array(
					array(
						$fileCollection,
					),
				),
			));
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}
	
	/**
	 * @param $data
	 * @return string
	 */
	public function photo($data): string
	{
		$li = "";
		foreach ($data as $num => $array) {
			//编辑表单
			$click = '';
			if (!empty($array['id'])) {
				$click = "<img  src='" . root . "img/images/clickEdit.png' onClick=\"clickUpload('{$array['type']}','{$array['id']}')\" class='clickIco edit-ico'>";
				if (!empty($array['fileId'])) {
					$click = "<img  src='" . root . "img/control/singleDel.svg' onClick=\"delSingleIco('{$array['fileId']}')\" class='clickIco edit-ico'>";
				}
			}
			//点击显示大图功能
			if (empty($array['url'])) {
				$img = "<img class='smallImg imgHover' data-type='{$array['type']}' src='" . root . "img/images/emptyImg.jpg'>";
			} else {
				if (strstr($array['url'], "http") !== false) {
					$r = "";
				} else {
					$r = root;
				}
				$img = "<a target='_blank' href='" . $r . $array['url'] . "' title='点击查看大图'><img data-type='{$array['type']}' class='smallImg imgHover' src='" . $r . $array['url'] . "'></a>";
			}
			//打印本图像框
			$li .= "
			<li>
				" . $click . "
				<p>" . $array['title'] . "</p>
				<div>" . $img . "</div>
			</li>
			";
		}
		$html = <<<efo
		<div class='imgSingle'>
			<ul>{$li}</ul>
			<div class='clear'></div>
		</div>
		<div class='hidden'>
            <form name="imgForm">
                <input type="hidden" name="mainId">
                <input type="hidden" name="type">
                <input name='ico' id='ico' type='file' onchange="uploadImgFile('imgForm',root+'control/adIndex.html?cla={$this->get('cla')}&fun=uploadIco','add-file-button')">
            </form>
		</div>
		<script>
		//点击上传图片
        function clickUpload(type,id){
            $('[name=mainId]').val(id)
            $('[name=type]').val(type)
            $('#ico').click();
        }
        //上传图片
        function uploadImgFile(formName,url){
            let form = $("form[name='"+formName+"']")[0];
            let type= $('[name=type]').val();
            let formData = new FormData(form);
            $.ajax({
                type: "POST",
                contentType: false,
                processData: false,
                url: url,
                data: formData,
                cache: false,
                success: function (res) {
                    let result = JSON.parse(res);
                    $("[name='ico']").val('');
                    if (result.warn === 2) {
                        $("[data-type='"+type+"']").attr('src',result.data.src);
                        $("[data-type='"+type+"']").parent().parent().find(".edit-ico").attr('src',root+'img/control/singleDel.svg');
                        $("[data-type='"+type+"']").parent().parent().find(".edit-ico").attr('onclick',"delSingleIco('"+result.data.id+"')")
                    }else{
                        warn(result.warn)
                    }
                },
                error: function (e) {
                    warn("上传失败");
                }
            });
        }
        </script>
efo;
		return $html;
	}
	
	/**
	 *上传图像资料
	 */
	function uploadIco()
	{
		$type   = $this->post('type');
		$result = $this->saveFile($_FILES['ico'], 'staff', explode(',', para('fileFormat')));
		$info   = query(self::table, " stid = '{$this->post('mainId')}'");
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = L('staffProfiles.tip.permission_edit_warn');
		} elseif (empty($info['stid'])) {
			$json['warn'] = L('staffProfiles.detail.find_none_staff');
		} elseif (empty($type)) {
			$json['warn'] = L('staffProfiles.tip.find_none_type');
		} elseif (!$result['code']) {
			$json['warn'] = $result['warn'];
		} else {
			$field        = match ($type) {
				'头像'   => 'ico',
				'工资卡' => 'bankIco'
			};
			$json['warn'] = static::update(array("table" => self::table, "field" => array($field => $result['src']), "where" => " stid = '" . $this->post('mainId') . "' "));
			//添加日志
			if ($json['warn'] == "更新成功") {
				if ($info[$field] != 'img/websiteImg/replaceHead.jpg') {
					fileDelete($info[$field]);//删除之前的图片
				}
				
				$json['warn']        = 2;
				$json['data']['src'] = root . $result['src'];
			}
		}
		return json_encode($json, 320);
	}
	
	/**
	 * 资产领用
	 *
	 * @return bool|string
	 */
	public function asset()
	{
		$endDate = $this->date;
		$staff   = query('staff', "stid = '" . $this->get('id') . "'");
		$sql     = find(array('table' => " `asset_use_detail` as a join `asset_use` as b on a.orderId = b.id", 'field' => " b.receivingDate,a.*", 'where' => " b.state = '已通过' and b.receiver = '$staff[stid]' and a.state != '已归还' order by time desc"));
		$tr[]    = array(
			L('staffProfiles.detail.pickDate'),
			L('staffProfiles.detail.asset_orderNo'),
			L('staffProfiles.detail.assetName'),
			L('staffProfiles.detail.brand'),
			L('staffProfiles.detail.model'),
			L('staffProfiles.detail.remind_value') . "（" . static::$unit . "）",
		);
		foreach ($sql['array'] as $array) {
			$asset         = query('asset', " id = '$array[atid]'");
			$ratio         = assetManagementClass::monthRatio($asset['depreciationMethod'], $asset['discountYear'], $asset['money'], $asset['purchaseMoney'], $asset['depreciationMoney'], $asset['purchaseDate'], $endDate, 1);
			$monthDecMoney = assetManagementClass::monthDecMoney($asset['depreciationMethod'], $asset['purchaseMoney'], $ratio / 100, $asset['purchaseDate'], $endDate, $asset['discountYear'], $asset['money'], $asset['depreciationMoney']);
			$salvage       = assetManagementClass::calcRemindMoney($asset['depreciationMethod'], $monthDecMoney, $asset['purchaseDate'], $asset['discountYear'], $asset['purchaseMoney'], $asset['money'], $asset['depreciationMoney'], $endDate);
			$tr[]          = array($array['receivingDate'], $asset['orderNo'], $asset['name'], $asset['brand'], $asset['model'], $salvage);
		}
		//构建表单
		$json['html'] = space . "<form name='assetForm'>" . $this->tableMany(array("tr" => $tr)) . "</form>";
		//返回
		return json_encode($json, 320);
	}
	
	/**
	 * 变动记录
	 */
	public function record()
	{
		$html         =
			text(array("name" => "orderNo", "title" => L('staffProfiles.detail.orderNo'))) .
			select(array("name" => "type", "title" => L('staffProfiles.detail.orderType'), 'option' => ['入职', '转正', '调岗', '停薪留职', '离职'])) .
			text(array("name" => "recordDate", 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('staffProfiles.detail.date') . "-" . L('staffProfiles.detail.date'))) .
			hidden(array('name' => 'id', 'value' => $this->get('id')));
		$json['html'] = $this->search($html);
		return json_encode($json, 320);
	}
	
	/**
	 * 变动记录
	 *
	 * @return bool|string
	 */
	public function recordSearch()
	{
		$id    = $this->post('id');
		$where = " and stid = '$id'";
		$and   = '';
		$like  = [
			'orderNo' => $this->post('orderNo'),
		];
		$equal = [
			'type' => $this->post('type'),
		];
		if ($this->post('recordDate')) {
			$timeArr = explode(' ~ ', $this->post('recordDate'));
			$and     .= " and recordDate >='{$timeArr[0]}' and  recordDate <='{$timeArr[1]}'";
		}
		
		$where .= search(["like" => $like, "=" => $equal]) . $and;
		$page  = $this->page([
			"table" => "staff_state_record",
			"where" => " {$where} ",
			"order" => " recordDate desc,`time` desc",
		]);
		//获取表头
		$tr[] = ['', L('staffProfiles.detail.orderType'), L('staffProfiles.detail.orderNo'), L('staffProfiles.detail.date')];
		//获取记录
		foreach ($page['array'] as $array) {
			$cla = match ($array['type']) {
				'入职'     => 'staffEntryRecord',
				'离职'     => 'staffQuitRecord',
				'停薪留职' => 'staffStayRecord',
				'调岗'     => 'jobApply',
				'转正'     => 'staffFormal',
				default    => '',
			};
			if ($cla) {
				//跳转路径
				$url      = root . 'control/adIndex.html?cla=' . $cla . '&&fun=detail&id=' . $array['sourceId'];
				$dominate = array(
					"detail" => array("title" => "详情", "click" => "newIframe('" . $array['type'] . "详情','" . $url . "')"),
				);
			} else {
				$dominate = [];
			}
			$tr[] = array(
				$this->dominate($dominate),
				$array['type'],
				$array['orderNo'],
				$array['recordDate'],
			);
		}
		//控件
		$button       = "";
		$json['html'] = $page['hint'] . $button . "<form name='topicForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'];
		return json_encode($json, 320);
	}
	
	/**
	 * 员工设置
	 *
	 * @return bool|string
	 */
	public function setting()
	{
		$staff = query('staff', "stid = '" . $this->get('id') . "'");
		if (!$this->power(self::page, "see")) {
			$json['html'] = L('staffProfiles.tip.permission_see_warn');
		} else {
			$user = query('user', " stid = '$staff[stid]'");
			if ($this->power(self::page, "edit")) {
				$photo = array(
					array("title" => L('staffProfiles.detail.portrait'), 'type' => '头像', "url" => $staff['ico'], "id" => $staff['stid']),
					array("title" => L('staffProfiles.detail.pay_card'), 'type' => '工资卡', "url" => $staff['bankIco'], "id" => $staff['stid']),
				);
				//薪酬编辑按钮
				$salaryButton  = "<span style='margin-left: 20px;cursor: pointer' onclick=\"layer('{$this->get('cla')}','salary',{id:'" . $staff['stid'] . "'})\"><img style='width:16px;height:16px' src='" . root . "img/control/edit.svg'></span>";
				$accountButton = "<span style='margin-left: 20px;cursor: pointer' onclick=\"layer('{$this->get('cla')}','accountSet',{id:'" . $staff['stid'] . "'})\"><img style='width:16px;height:16px' src='" . root . "img/control/edit.svg'></span>";
				$userButton    = "<span style='margin-left: 20px;cursor: pointer' onclick=\"layer('{$this->get('cla')}','userSet',{id:'" . $staff['stid'] . "'})\"><img style='width:16px;height:16px' src='" . root . "img/control/edit.svg'></span>";
			} else {
				$photo         = array(
					array("title" => L('staffProfiles.detail.portrait'), 'type' => '头像', "url" => $staff['IDCardFront']),
					array("title" => L('staffProfiles.detail.pay_card'), 'type' => '工资卡', "url" => $staff['IDCardBack']),
				);
				$salaryButton  = '';
				$accountButton = '';
				$userButton    = '';
			}
			
			$field = array(
				L('staffProfiles.detail.salary_setting') . $salaryButton  => array(
					array(
						L('staffProfiles.detail.bankName') => $staff['bankName'],
						L('staffProfiles.detail.bankNo')   => $staff['bankNum'],
					),
					array(
						L('staffProfiles.detail.personal_part') . "(" . static::$unit . ")" => $staff['personalFund'],
						L('staffProfiles.detail.company_part') . "(" . static::$unit . ")"  => $staff['companyFund'],
					),
				),
				L('staffProfiles.detail.account_stting') . $accountButton => array(
					
					array(
						L('staffProfiles.detail.ding')      => $staff['dingtalkId'],
						L('staffProfiles.detail.wechat_id') => $user['weChatUserId'],
					),
				),
			
			);
			if (!empty($user['uid'])) {
				$field = array_merge($field,
					[
						L('staffProfiles.detail.user_stting') . $userButton => array(
							
							array(
								L('staffProfiles.detail.username') => $user['userName'],
							),
							array(
								L('staffProfiles.detail.role') => $this->findRoleName($user['role']),
							),
							array(
								L('staffProfiles.table.text') => $user['text'],
							),
						),
					]);
			} else {
				$field = array_merge($field,
					[
						L('staffProfiles.detail.user_stting') => array(

//                            array(
//                                "<span class='del-row-button' onclick=\"newIframe('新建用户', '" . $this->root . "control/adIndex.html?cla=user&fun=editPage&staffId=".$staff['stid']."')\">新建</span>",
//                            ),
array(
	"<span class='del-row-button' onclick=\"layer('" . self::page . "', 'userSet',{id:'" . $staff['stid'] . "'})\">新建</span>",
),
						),
					]
				);
			}
			$field        = array_merge($field, [
				L('staffProfiles.detail.picture') => array(
					array(
						$this->photo($photo),
					),
				),
			]);
			$json['html'] = $this->tableShow($field);
		}
		//返回
		$json['html'] .= <<<efo
<script>
//获取钉钉ID
function getDingId(id) {
     let con = setTimeout(function (){
        $("#loading", parent.document).hide();
    },15000);
    $("#loading", parent.document).show();
   $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getDingId',{id:id},function(res) {
       if (res.errcode ===0){
           $('[name=dingtalkId]').val(res.data);
       }else{
           warn(res.warn);
       }
         $("#loading", parent.document).hide();
            clearTimeout(con);
   },'json')
}
function getWechatUserId(id) {
      let con = setTimeout(function (){
        $("#loading", parent.document).hide();
    },15000);
       $("#loading", parent.document).show();
   $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getWechatUserId',{id:id},function(res) {
       if (res.errcode ===0){
           $('[name=weChatUserId]').val(res.data);
       }else{
           warn(res.warn);
       }
         $("#loading", parent.document).hide();
            clearTimeout(con);
   },'json')
}
</script>
efo;
		
		return json_encode($json, 320);
	}
	
	/**
	 * 根据手机号获取钉钉ID
	 *
	 * @return bool|string
	 */
	public function getDingId()
	{
		$id     = $this->post('id');
		$staff  = query('staff', " stid = '$id'");
		$obj    = new workSignCheckClass();
		$userId = $obj->getbymobile($staff['tel']);
		if (empty($userId)) {
			$json['errcode'] = 1;
			$json['warn']    = L('staffProfiles.tip.find_none_ding');
		} else {
			$json['errcode'] = 0;
			$json['warn']    = '';
			$json['data']    = $userId;
		}
		return json_encode($json, 320);
	}
	
	/**
	 * 根据手机号获取企业微信ID
	 *
	 * @return bool|string
	 */
	public function getWeChatUserId(): bool|string
	{
		$id     = $this->post('id');
		$staff  = query('staff', " stid = '$id'");
		$userId = $this->getWechatUserIdByTel($staff['tel']);
		if (empty($userId)) {
			$json['errcode'] = 1;
			$json['warn']    = L('staffProfiles.tip.find_none_wechat');
		} else {
			$json['errcode'] = 0;
			$json['warn']    = '';
			$json['data']    = $userId;
		}
		return json_encode($json, 320);
	}
	
	/**
	 * 用户设置
	 *
	 * @return bool|string
	 */
	public function userSet()
	{
		$staff = query('staff', " stid = '{$this->post('id')}'");
		$user  = query('user', " stid = '$staff[stid]'");
		//获取角色
		$result     = find(array('table' => "role order by list,time asc"));
		$roleOption = [];
		foreach ($result['array'] as $array) {
			$roleOption[$array['id']] = $array['name'];
		}
		//生成表单
		$html = $this->layerEdit(array(
			"table" => array(
				array(
					must . L('staffProfiles.detail.username') . "：" => text(array("name" => "userName", "value" => $user['userName'] ?: $staff['name'])),
				),
				array(
					L('staffProfiles.detail.password') . "：" => hidden(['name' => 'password', 'value' => '']) . (!empty($user['uid']) ? "<span id='pwd'>***********</span><span class='spanButton' style='margin: 0 0 0 20px' id='resetPas'>" . L('staffProfiles.detail.pwd_reset_copy') . "</span>" : para('staffPas') . ' (初始密码)') . "
<script src='{$this->root}static/javascript/clipboard.min.js'></script>
<script>
 var clipboard = new ClipboardJS('#resetPas', {
        text: function() {
            resetPwd();
            return $('#pwd').html();
        }
    });
    clipboard.on('success', function(e) {
       msg('" . L('staffProfiles.detail.pwd_copy') . "')
    });
 function resetPwd(){
        $.ajax({
            url: root + 'control/adIndex.html?cla=staffProfiles&fun=resetPwd',
            type: 'post',
            data: {
                id : $('[name=\"id\"]').val()
            },
            dataType: 'json',
            async: false,
            success: function(res) {
                if(res.code == 1){
                    $('#pwd').html(res.data)
                }else{
                    msg(res.msg, 'error')
                }
            }
        });
 }
</script>
",
				),
				array(
					must . L('staffProfiles.detail.role') . "：" => "<pre>" . checkbox(array('name' => 'role', 'value' => $roleOption, 'checked' => json_decode($user['role'], true))) . "</pre>",
				),
				array(
					L('staffProfiles.table.text') . '：' => textarea(array('name' => 'text', 'class' => 'textarea', 'value' => $user['text'])),
				),
			),
		));
		//返回
		return $this->layer(array("title" => L('staffProfiles.detail.user_stting'), "height" => 514, "width" => 900, "html" => $html));
	}
	
	/**
	 * 重置密码
	 *
	 * @return bool|string
	 */
	public function resetPwd(): bool|string
	{
		$id           = $this->post('id');
		$staff        = query(self::table, "stid = '$id'");
		$data['code'] = 0;
		$user         = query('user', "stid = '$staff[stid]'");
		if (empty($staff['stid'])) {
			$data['msg'] = L('staffProfiles.detail.find_none_staff');
		} elseif (!$this->power(self::page, "edit")) {
			$data['msg'] = L('staffProfiles.tip.permission_edit_warn');
		} elseif (empty($user['uid'])) {
			$data['msg'] = L('staffProfiles.detail.find_none_account');
		} else {
			$password     = para('staffPas');
			$data['warn'] = static::update([
				'table' => 'user',
				'field' => [
					'password' => md5s($password),
				],
				'where' => " uid = '$user[uid]' ",
			]);
			if (in_array($data['warn'], ['更新成功', '新增成功'])) {
				$data = [
					'msg'  => L('staffProfiles.detail.pwd_reset'),
					'data' => $password,
					'code' => 1,
				];
			}
		}
		return json_encode($data, 320);
	}
	
	/**
	 * 用户设置
	 *
	 * @return bool|string
	 */
	public function userSetEdit()
	{
		$id         = $this->post('id');
		$staff      = query(self::table, " stid = '" . $id . "' ");
		$user       = query('user', " stid = '$staff[stid]'");
		$field      = [
			'stid'       => $staff['stid'],
			'name'       => $staff['name'],
			'tel'        => $staff['tel'],
			'userName'   => $this->post('userName'),
			'role'       => $this->post('role') ? json_encode($this->post('role'), 320) : [],
			'text'       => $this->post('text'),
			'updateTime' => $this->time,
		];
		$annotation = [
			'userName' => L('staffProfiles.detail.username'),
			'role'     => L('staffProfiles.detail.role'),
		];
		$rules      = [
			'stid'     => 'required',
			'name'     => 'required',
			'userName' => 'required',
			'role'     => 'required',
			'tel'      => 'required|unsigned_int',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = L('staffProfiles.tip.permission_edit_warn');
		} elseif (empty($staff['stid'])) {
			$json['warn'] = L('staffProfiles.detail.find_none_staff');
		} elseif ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
		} elseif (static::total(array('table' => 'user', 'where' => "userName = '$field[userName]' and stid !='$staff[stid]'")) > 0) {
			$json['warn'] = L('staffProfiles.detail.exist_user');
		} else {
			// 非无限用户 设定用户数
			$users = (int)para('userNumberLimit');
			if ($users != -1) {
				// 已有用户数
				$total = static::total(['table' => 'user', 'where' => " 1=1 "]);
				if ($total >= $users) {
					$json['warn'] = str_replace(['{{num}}'], [$users], L('setting.table.user_new_warn'));
					goto resp;
				}
			}
			if (sqlNum('user', " (userName = '{$field['userName']}' OR tel = '{$field['tel']}') AND stid <> '$id'   ") > 0) {
				$json['warn'] = str_replace(['{{name}}', '{{tel}}'], [$field['userName'], $field['tel']], L('setting.table.user_repeat'));
				goto resp;
			}
			
			if (!$user['uid']) {
				$userNo       = codeTemplateClass::generateCode('user', [
					'prefix' => 'UID' . date('Ymd'),
					'table'  => 'user',
					'field'  => 'userNo',
					'where'  => '',
				], $field);
				$field        = array_merge($field, [
					'uid'      => $id,
					'userNo'   => $userNo,
					'password' => md5s(para('staffPas')),
					'operator' => $this->control['stid'],
					'state'    => '启用',
					'time'     => $this->time,
				]);
				$json['warn'] = static::insert(["table" => 'user', "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => 'user',
					"field" => $field,
					"where" => "uid = '$user[uid]'",
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加日志
				$text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $staff['name'], $staff['stid']], L('staffProfiles.other.user_edit_log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=setting&id=" . $staff['stid'];
			}
		}
		//返回
		resp:
		return json_encode($json, 320);
	}
	
	/**
	 * 第三方账号设置
	 *
	 * @return bool|string
	 */
	public function accountSet()
	{
		$staff = query('staff', " stid = '{$this->post('id')}'");
		$user  = query('user', "stid = '$staff[stid]'");
		//生成表单
		$html = $this->layerEdit(array(
			"table" => array(
				array(
					L('staffProfiles.detail.ding') . "：" => text(array("name" => "dingtalkId", "value" => $staff['dingtalkId'])) . "<span class='spanButton' style='margin: 0' onclick=\"getDingId('{$staff['stid']}')\">" . L('staffProfiles.detail.get') . "</span>" . componentClass::tipComponent(L('staffProfiles.detail.dingSameTel')),
				),
				array(
					L('staffProfiles.detail.wechat_id') . "：" => text(array("name" => "weChatUserId", "value" => $user['weChatUserId'])) . "<span class='spanButton' style='margin: 0' onclick=\"getWechatUserId('{$staff['stid']}')\">" . L('staffProfiles.detail.get') . "</span>" . componentClass::tipComponent(L('staffProfiles.detail.wechatSameTel')),
				),
			),
		));
		//返回
		return $this->layer(array("title" => L('staffProfiles.detail.account_stting'), "height" => 245, "width" => 700, "html" => $html));
	}
	
	/**
	 * 第三方账号设置
	 *
	 * @return bool|string
	 */
	public function accountSetEdit()
	{
		$field = [
			'dingtalkId' => $this->post('dingtalkId'),
			'updateTime' => $this->time,
		];
		
		$staff = query(self::table, " stid = '" . $this->post('id') . "' ");
		$user  = query('user', "stid = '$staff[stid]'");
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = L('staffProfiles.tip.permission_edit_warn');
		} elseif (empty($staff['stid'])) {
			$json['warn'] = L('staffProfiles.detail.find_none_staff');
		} elseif (!$user['uid'] && $this->post('weChatUserId')) {
			$json['warn'] = L('staffProfiles.detail.user_account_warn');
		} else {
			$this->startTrans();
			//更新员工档案
			$json['warn'] = update(array(
				"table" => "staff",
				"field" => $field,
				"where" => "stid = '$staff[stid]'",
			));
			$bool         = update(array('table' => 'user', 'field' => ['weChatUserId' => $this->post('weChatUserId')], 'where' => "stid = '$staff[stid]'"));
			if ($bool != '更新成功') {
				$json['warn'] = $bool;
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				$this->commitTrans();
				//添加日志
				$text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $staff['name'], $staff['stid']], L('staffProfiles.other.account_edit_log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=setting&id=" . $staff['stid'];
			} else {
				$this->rollback();
			}
		}
		//返回
		return json_encode($json, 320);
	}
	
	/**
	 * 薪酬设置
	 */
	public function salary()
	{
		$staff = query('staff', " stid = '{$this->post('id')}'");
		//生成表单
		$html = $this->layerEdit(array(
			"table" => array(
				array(
					must . L('staffProfiles.detail.bankName') . "：" => text(array("name" => "bankName", "value" => $staff['bankName'])),
				),
				array(
					must . L('staffProfiles.detail.bankNo') . "：" => text(array("name" => "bankNum", "value" => $staff['bankNum'])),
				),
				//            array(
				//                L('staffProfiles.detail.buy_insure')."：" => radio(array('name' => 'socialSecurity', 'value' => ['是', '否'], 'checked' => $staff['socialSecurity'] ?: '是')),
				//            ),
				//            array(
				//                L('staffProfiles.detail.insureNo')."：" => text(array("name" => "socialSecurityNum", "value" => $staff['socialSecurityNum'])),
				//            ),
				array(
					L('staffProfiles.detail.personal_part') . "：" => text(array("name" => "personalFund", 'class' => 'text', 'unit' => static::$unit, "value" => $staff['personalFund'])),
				),
				array(
					L('staffProfiles.detail.company_part') . "：" => text(array("name" => "companyFund", 'class' => 'text', 'unit' => static::$unit, "value" => $staff['companyFund'])),
				),
			),
		));
		//返回
		return $this->layer(array("title" => L('staffProfiles.detail.salary_setting'), "height" => 342, "html" => $html));
	}
	
	/**
	 * 薪酬设置编辑
	 *
	 * @return bool|string
	 */
	public function salaryEdit()
	{
		$field      = [
			'bankName'     => $this->post('bankName'),
			'bankNum'      => $this->post('bankNum'),
			//            'socialSecurity' => $this->post('socialSecurity'),
			//            'socialSecurityNum' => $this->post('socialSecurityNum'),
			'personalFund' => $this->post('personalFund'),
			'companyFund'  => $this->post('companyFund'),
			'updateTime'   => $this->time,
		];
		$annotation = [
			'bankName' => L('staffProfiles.detail.bankName'),
			'bankNum'  => L('staffProfiles.detail.bankNo'),
		];
		$rules      = [
			'bankName' => 'required',
			'bankNum'  => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		$staff  = query(self::table, " stid = '" . $this->post('id') . "' ");
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = L('staffProfiles.tip.permission_edit_warn');
		} elseif (empty($staff['stid'])) {
			$json['warn'] = L('staffProfiles.detail.find_none_staff');
		} elseif ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
		} else {
			//更新员工档案
			$json['warn'] = update(array(
				"table" => "staff",
				"field" => $field,
				"where" => "stid = '$staff[stid]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加日志
				$text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $staff['name'], $staff['stid']], L('staffProfiles.other.salary_edit_log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=setting&id=" . $staff['stid'];
			}
		}
		//返回
		return json_encode($json, 320);
	}
	
	
	/**
	 * 样式
	 */
	private function style(): string
	{
		return <<<eof
<style>
.tag-contain-title{border-bottom: 1px solid #d7d7d7;padding: 5px}
.tag-contain-title img{cursor: pointer}
.tag-list-ul>li{float: left;padding: 5px;margin: 5px}
.tag-contain{width: 500px;height: 400px;padding: 10px;border: 1px solid #d7d7d7;border-radius: 2px;position: relative;overflow: hidden}
.tag-contain-title-text{margin-left: 10px;font-size: 14px}
.tag-contain-ul li{margin: 5px 5px}
.tag-contain-foot{margin: 10px;padding: 10px;border-bottom: 1px solid #d7d7d7}
.tag-contain-body{width: 480px;height: 370px;margin: 0 auto}

}
</style>
eof;
	}
	
	public function evaluation()
	{
		$edit  = $del = '';
		$id    = $this->get('id');
		$staff = query('staff', "stid = '$id'");
		$sql   = find(array("table" => "talent_pool_interview", "where" => " talentId in ('" . $id . "','" . $staff['talentId'] . "') order by recordDate desc "));
		$url   = root . "control/adIndex.html?cla=" . self::page;
		//获取记录
		$html = "<ul class='tag-list-ul'>";
		$root = root;
		foreach ($sql['array'] as $array) {
			$creatName = self::findStaff($array['managerId']);
			
			$node  = $array['node'] == '其他节点' ? $array['node'] . '-' . $array['nodeText'] : $array['node'];
			$all   = find(array('table' => 'talent_pool_interview_detail', 'where' => "orderId = '$array[id]' order by list"));
			$xData = [];
			$yData = [];
			foreach ($all['array'] as $val) {
				$job_model_detail = query('job_model_detail', "id = '$val[modelId]'");
				$xData[]          = [
					'name' => $job_model_detail['name'],
					'max'  => 100,
				];
				$yData[]          = $val['score'];
			}
			
			$data                            = [
				"xData" => $xData,
				"yData" => [
					'name' => '',
					'data' => $yData,
				],
			];
			$salesPerformanceStatisticsClass = new salesPerformanceStatisticsClass();
			$echart                          = $salesPerformanceStatisticsClass->radarChart($data);
			if ($array['type'] == '评价记录') {
				$title      = '员工档案';
				$directUrl  = $url . "&fun=info&staffId={$array['talentId']}&id={$array['id']}";
				$infoUrl    = $url . "&fun=infoDetail&id={$array['id']}";
				$editButton = "<img onclick=\"newIframe('{$title}','{$directUrl}')\"  src=\"{$root}img/control/edit.svg\">";
				$box        = "<input name=\"faceId[]\" type=\"checkbox\" value=\"$array[id]\">";
			} else {
				$title      = '人才库';
				$infoUrl    = root . "control/adIndex.html?cla=talentPool&fun=infoDetail&id={$array['id']}";
				$editButton = '';
				$box        = '';
			}
			$evaluation_node = L('staffProfiles.detail.evaluation_node');
			$evaluator       = L('staffProfiles.detail.evaluator');
			$evaluate_date   = L('staffProfiles.detail.evaluate_date');
			$html            .= <<<efo
<li>
     <div class="tag-contain">
           <div class="tag-contain-title">
                 {$box}
                 {$editButton}
                 <img onclick="newIframe('{$title}','{$infoUrl}')" alt="" src="{$root}img/control/detail.svg">
                 <span class="tag-contain-title-text">{$evaluation_node}：$node</span>
                 <span class="tag-contain-title-text">{$evaluator}：$creatName</span>
                 <span class="tag-contain-title-text">{$evaluate_date}：{$array['recordDate']}</span>
           </div>
           <div class="tag-contain-body">
           {$echart}
           </div>
     </div>
</li>
efo;
		}
		$no_data = L('staffProfiles.detail.no_data');
		if (is_array($sql['array']) && count($sql['array']) == 0) {
			$html .= <<<eof
<div class="container-no">
                    <img class="container-no-img" src="{$this->root}img/control/department-no.svg">
                    <p class="center gray">$no_data</p>
                </div>
eof;
		}
		
		$html .= <<<efo
</ul>
efo;
		$html .= $this->style();
		
		
		if ($this->power(self::page, "interviewEdit")) {
			$edit = "<span class='spanButton' title='" . L('job.model.edit') . "' onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=info&staffId={$id}')\">" . L('job.model.edit') . "</span>\n";
		}
		if ($this->power(self::page, "interviewDel")) {
			$del = "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'delInterview'})\">" . L('staffProfiles.button.del') . "</span>\n";
		}
		$json['html'] = $edit . $del . space . "<script src='{$this->root}static/javascript/echarts.min.js'></script><form name='faceForm'>" . $html . "</form>";
		return json_encode($json, 320);
	}
	
	/*详情页*/
	public function infoDetail(): string
	{
		$info = query('talent_pool_interview', " id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = L('staffProfiles.detail.find_none_ev_record');
		} else {
			//菜单
			$data = array(
				"id" => $info['id'],
			);
			
			$button = [];
			if ($this->power(self::page, "interviewEdit")) {
				//按钮
				$button[] = [
					"name"  => L('staffProfiles.button.edit'),
					"type"  => "顶部页卡",
					"title" => L('staffProfiles.button.edit'),
					"url"   => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=info&staffId=' . $info['talentId'] . '&id=' . $info['id'],
					'style' => 'li-btn-blue-bg',
				];
			}
			if ($this->power(self::page, "interviewDel")) {
				//按钮
				$button[] = [
					"name" => L('staffProfiles.button.del'),
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'delInterview', "id" => $info['id']],
				];
			}
			
			$result     = find(array('table' => 'talent_pool_interview_detail', 'where' => "orderId = '$info[id]' order by list asc"));
			$tr[]       = [
				L('job.model.projectName'),
				L('job.model.projectText'),
				L('job.model.evaluate_item'),
				L('job.model.percent'),
				L('staffProfiles.detail.score'),
			];
			$totalScore = 0;
			foreach ($result['array'] as $array) {
				$mx             = query('job_model_detail', "id = '$array[modelId]'");
				$tr[]           = [
					$mx['name'],
					$mx['text'],
					$array['itemName'],
					($mx['proportion'] * 100) . '%',
					"<span class='score'>{$array['score']}</span>",
				];
				$array['score'] = $array['score'] ?: 0;
				$totalScore     += $array['score'] * $mx['proportion'];
			}
			$tr[]             = [L('staffProfiles.detail.all_score'), ' ', ' ', ' ', "<span id='totalScore'>" . ($totalScore ?: '---') . "</span>"];
			$staff            = query(self::table, "stid = '$info[talentId]'");
			$talent           = query('talent_pool', "id = '$staff[talentId]'");
			$job              = query('job', "id = '$staff[jobId]'");
			$staffEntryRecord = query('staff_entry_record', "talentId = '$staff[talentId]' order by time desc");
			//生成表单
			$data['html'] = $this->tableShow(array(
				"button"                                  => $button,
				L('staffProfiles.detail.evd_information') => array(
					array(
						L('staffProfiles.table.name') => $talent['name'],
						L('staffProfiles.table.sex')  => $talent['sex'],
						L('staffProfiles.table.age')  => $this->age($talent['birthDay']),
					),
					array(
						L('staffProfiles.table.college')   => $talent['college'],
						L('staffProfiles.table.major')     => $talent['major'],
						L('staffProfiles.table.education') => $talent['education'],
					),
					array(
						L('staffProfiles.table.department') . "：" => departmentClass::getTypeName($job['departmentId']),
						L('staffProfiles.table.job') . '：'        => $job['name'],
						L('staffProfiles.table.entryDate') . '：'  => $staffEntryRecord['entryDate'],
					),
				),
				L('staffProfiles.detail.ev_information')  => array(
					array(
						L('staffProfiles.detail.evaluate_date') => $info['recordDate'],
						L('staffProfiles.detail.evaluator')     => self::findStaff($info['managerId']),
					),
				),
				L('staffProfiles.detail.assessment')      => array(
					array(
						$this->tableMany(array('tr' => $tr)),
					),
				),
				L('staffProfiles.detail.all_evaluation')  => array(
					array(
						L('staffProfiles.detail.all_evaluation') => $info['evaluation'],
					),
					array(
						L('staffProfiles.detail.evaluation_result') => $info['opinion'],
					),
				),
				L('staffProfiles.table.enclosure')        => array(
					array(
						fileUploadClass::showFile($info['id']),
					),
				),
			));
			
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}
	
	public function info()
	{
		$id               = $this->get('id') ?: suiji();
		$stid             = $this->get('staffId');
		$info             = query('talent_pool_interview', " id = '" . $id . "' ");
		$staff            = query(self::table, "stid = '$stid'");
		$talent           = query('talent_pool', "id = '$staff[talentId]'");
		$staffEntryRecord = query('staff_entry_record', "talentId = '$staff[talentId]' order by time desc");
		//按钮
		$button[] = [
			"name"  => L('staffProfiles.table.save'),
			"type"  => "点击事件",
			"cla"   => $this->get('cla'),
			"fun"   => "subForm('" . self::page . "InfoForm',root+'control/adIndex.html?cla=" . self::page . "&fun=infoEdit')",
			"post"  => ["id" => $id],
			'style' => 'li-btn-blue-bg',
		];
		$job      = query('job', "id = '$staff[jobId]'");
		//能力评定
		$tr[]       = [
			L('job.model.projectName'),
			L('job.model.projectText'),
			L('job.model.evaluate_item'),
			L('job.model.percent'),
			L('staffProfiles.detail.score'),
		];
		$all        = find(array('table' => 'job_model_detail', 'where' => "jobId = '$staff[jobId]' order by time asc"));
		$totalScore = 0;
		foreach ($all['array'] as $array) {
			$mx          = query('talent_pool_interview_detail', "orderId = '$info[id]' and modelId = '$array[id]'");
			$tr[]        = [
				hidden(array('name' => 'detailId[]', 'value' => $array['id'])) .
				hidden(array('name' => 'proportion[]', 'value' => $array['proportion'])) .
				$array['name'],
				$array['text'],
				repeatSelect(array('name' => 'itemName[]', 'change' => 'getScore', 'sqlField' => 'name', 'sqlForm' => "job_model_item where orderId = '$array[id]' order by any_value(list)", 'title' => L('staffProfiles.table.choose'), 'value' => $mx['itemName'])),
				($array['proportion'] * 100) . '%',
				"<span class='score'>{$mx['score']}</span>",
			];
			$mx['score'] = $mx['score'] ?: 0;
			$totalScore  += $mx['score'] * $array['proportion'];
		}
		$tr[]         = [L('staffProfiles.detail.all_score'), ' ', ' ', ' ', "<span id='totalScore'>" . ($totalScore ?: '---') . "</span>"];
		$nodeOption   = explode('，', para('nodeOption'));
		$nodeOption[] = '其他';
		//表单
		$data['html'] = $this->layerEdit([
			"table"  => [
				[
					$this->tableShowButton($button),
				],
				[
					"<span class='small-title'>" . L('staffProfiles.detail.evd_information') . "</span>",
				],
				[
					L('staffProfiles.table.name') . "：" => $staff['name'],
					L('staffProfiles.table.sex') . "："  => $talent['sex'],
					L('staffProfiles.table.age') . '：'  => $this->age($talent['birthDay']),
				],
				[
					L('staffProfiles.table.college') . "："   => $talent['college'],
					L('staffProfiles.table.major') . "："     => $talent['major'],
					L('staffProfiles.table.education') . "：" => $talent['education'],
				],
				[
					L('staffProfiles.table.department') . "：" => departmentClass::getTypeName($job['departmentId']),
					L('staffProfiles.table.job') . '：'        => $job['name'],
					L('staffProfiles.table.entryDate') . '：'  => $staffEntryRecord['entryDate'],
				],
				[
					"<span class='small-title'>" . L('staffProfiles.detail.ev_information') . "</span>",
				],
				[
					must . L('staffProfiles.detail.evaluate_date') . "："   => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
					must . L('staffProfiles.detail.evaluator') . "："       => selectMultiple(array('name' => 'managerId', 'value' => $info['managerId'] ?: self::$stid, 'title' => L('staffProfiles.table.choose'), 'sqlId' => 'stid', 'sqlField' => 'name', 'table' => 'staff', 'where' => "state !='离职' order by orderNo asc")),
					must . L('staffProfiles.detail.evaluation_node') . "：" => radio(array('name' => 'node', 'value' => $nodeOption, 'checked' => $info['node'])) . "&nbsp;" . text(array('name' => 'nodeText', 'title' => '其他节点说明', 'value' => $info['nodeText'])),
				],
				[
					"<span class='small-title'>" . L('staffProfiles.detail.assessment') . "</span>",
				],
				[
					$this->tableMany(array('tr' => $tr)),
				],
				[
					"<span class='small-title'>" . L('staffProfiles.detail.all_evaluation') . "</span>",
				],
				[
					must . L('staffProfiles.detail.all_evaluation') . "：" => textarea(array('name' => 'evaluation', 'class' => 'textarea', 'value' => $info['evaluation'])),
				],
				[
					must . L('staffProfiles.detail.evaluation_result') . "：" => radio(array('name' => 'opinion', 'checked' => $info['opinion'] ?: '合格', 'value' => ['合格', '不合格'])),
				],
				[
					"<div><span class='small-title'>" . L('staffProfiles.table.enclosure') . "</span></div>",
				],
				[
					fileUploadClass::addFileComponent($info['id'], '评价记录', self::page, self::page . 'InfoForm'),
				],
			],
			'hidden' => hidden(array('name' => 'id', 'value' => $id)) . hidden(array('name' => 'staffId', 'value' => $this->get('staffId'))),
			'button' => ' ',
		]);
		//返回
		$data['html'] .= <<<eof
<script>
function getScore(e) {
  let val = e.value;
  let modelId = $(e).parent().parent().find("[name='detailId[]']").val();
  $.post(root+'control/adIndex.html?cla=talentPool&fun=getScore',{name:val,modelId:modelId},function(res) {
      $(e).parent().parent().find(".score").html(res.data.score);
      $(e).parent().parent().find("[name='proportion[]']").val(res.data.rate);
      addScore();
  },'json')
}
function addScore(){
    let num = 0;
    let proportion = 0;
    $(".score").each(function() {
        proportion = Number($(this).parent().parent().find("[name='proportion[]']").val())
       num+=Number($(this).html())*proportion;
    })
    $("#totalScore").html(num.toFixed(1));
}
</script>
eof;
		
		return $this->tab($data);
	}
	
	public function infoEdit()
	{
		$id         = $this->post('id');
		$info       = query('talent_pool_interview', " id = '$id'");
		$staff      = query(self::table, "stid = '" . $this->post('staffId') . "'");
		$field      = [
			'recordDate' => $this->post('recordDate'),
			'managerId'  => $this->post('managerId'),
			'evaluation' => $this->post('evaluation'),
			'opinion'    => $this->post('opinion'),
			'workFlow'   => $this->post('workFlow'),
			'node'       => $this->post('node'),
			'nodeText'   => $this->post('node') == '其他' ? $this->post('nodeText') : '',
		
		];
		$annotation = [
			'recordDate' => L('staffProfiles.detail.evaluate_date'),
			'managerId'  => L('staffProfiles.detail.evaluator'),
			'evaluation' => L('staffProfiles.detail.all_evaluation'),
			'opinion'    => L('staffProfiles.detail.evaluation_result'),
			'node'       => L('staffProfiles.detail.evaluation_node'),
		];
		$rules      = [
			'recordDate' => 'required|date',
			'managerId'  => 'required',
			'evaluation' => 'required',
			'opinion'    => 'required',
			'node'       => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		$detailIdArr = $this->post('detailId') ?? [];
		$itemNameArr = $this->post('itemName');
		//附件
		$fileIdArr = $this->post('fileId');
		//判断
		if (!$this->power(self::page, "interviewEdit")) {
			$json['warn'] = L('staffProfiles.tip.staffEvEdit');
		} elseif (empty($staff['stid'])) {
			$json['warn'] = L('staffProfiles.detail.find_none_staff');
		} elseif (static::is_null_array($detailIdArr)) {
			$json['warn'] = L('staffProfiles.tip.find_none_item');
		} elseif (static::is_null_array($itemNameArr)) {
			$json['warn'] = L('staffProfiles.tip.evaluate_warn');
		} elseif ($field['node'] == '其他' && empty($field['nodeText'])) {
			$json['warn'] = L('staffProfiles.tip.evaluate_item_warn');
		} else {
			$this->startTrans();//开启事务
			if (empty($info['id'])) {
				$manager      = query('staff', "stid = '$field[managerId]'");
				$job          = query('job', "id = '$manager[jobId]'");
				$field        = array_merge($field, [
					'id'          => $id,
					'stid'        => self::$stid,
					'talentId'    => $staff['stid'],
					'type'        => '评价记录',
					'managerDept' => departmentClass::getTypeName($job['departmentId']),
				]);
				$json['warn'] = static::insert(array('table' => 'talent_pool_interview', 'field' => $field));
			} else {
				$json['warn'] = static::update(array(
					'table' => 'talent_pool_interview',
					'field' => $field,
					'where' => "id = '$info[id]'",
				));
			}
			delete(array('table' => 'talent_pool_interview_detail', 'where' => " orderId = '$id'"));
			foreach ($detailIdArr as $k => $val) {
				$job_model_item = query('job_model_item', "orderId = '" . $val . "' and name = '" . $itemNameArr[$k] . "'");
				$bool           = static::insert(array(
					'table' => 'talent_pool_interview_detail',
					'field' => [
						'id'       => suiji(),
						'orderId'  => $id,
						'modelId'  => $val,
						'itemName' => $itemNameArr[$k],
						'score'    => $job_model_item['score'],
					],
				));
				if ($bool != '新增成功') {
					$json['warn'] = L('staffProfiles.tip.editFailed');
					break;
				}
			}
			//添加主表ID到附件表
			if (is_array($fileIdArr)) {
				$bool = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
				if ($bool != '更新成功') {
					$json['warn'] = $bool;
				}
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				$this->commitTrans();//提交事务
				//添加日志
				$text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $staff['name'], $id], L('staffProfiles.tip.interview_log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=evaluation&id=" . $staff['stid'];
			} else {
				$this->rollback();//回滚
			}
		}
		resp:
		return json_encode($json, 320);
	}
	
	
	/**
	 * 获取角色名称
	 *
	 * @param $role
	 * @return string
	 */
	public function findRoleName($role): string
	{
		$roleArr  = json_decode($role, true);
		$roleText = '';
		foreach ($roleArr as $roleId) {
			$role     = query('role', " id = '$roleId'");
			$roleText .= ',' . $role['name'];
		}
		return $roleText ? ltrim($roleText, ',') : '';
	}
	
	
	// 操作中转
	public function operate()
	{
		$act  = $this->post('act') ?? '';
		$pwd  = false; // 需要密码
		$form = $power = $word = '';
		switch ($act) {
			case 'delInterview':
				$act      = 'del';
				$msg      = L('staffProfiles.tip.del_evaluate_record');
				$title    = self::table . 'DeleteInterview';
				$function = 'deleteMx';
				$form     = self::page . 'OperateForm, faceForm';
				$power    = '';
				break;
			case 'recover':
				$word     = true;
				$act      = 'edit';
				$msg      = L('staffProfiles.tip.confirmWork');
				$title    = L('staffProfiles.tip.is_confirm_work');
				$form     = self::page . 'OperateForm,detailForm';
				$function = 'recover';
				break;
			
			default:
				$act      = 'del';
				$msg      = L('staffProfiles.tip.del_staff');
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
			]);
		}
		
		resp:
		return json_encode($json, 320);
	}
	
	/**
	 * 确认上岗
	 *
	 * @return bool|string
	 */
	public function recover(): bool|string
	{
		$id   = $this->post('id');
		$info = query(self::table, " stid = '$id'");
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = L('staffProfiles.tip.permission_edit_warn');
		} elseif (empty($info['stid'])) {
			$json['warn'] = L('staffProfiles.detail.find_none_staff');
		} else {
			$field        = [
				'state' => '转正',
			];
			$json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " stid ='$id'"));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加上岗日期到记录表中
				$staffStayRecord = query('staff_stay_record', " staffId = '$info[stid]' and isConfirm = 1 and state = '已通过' order by endDate desc,time desc");
				update(array('table' => 'staff_stay_record', 'field' => ['recoverTime' => $this->time], 'where' => " id = '$staffStayRecord[id]'"));
				//生成员工变动记录
				$obj = new staffEntryRecordClass();
				$obj->insertStaffStateRecord($info['stid'], '上岗', $staffStayRecord['id'], $this->date);
				//添加日志
				$text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $info['name'], $id], L('staffProfiles.other.recover_edit_log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
			}
		}
		//返回
		return json_encode($json, 320);
	}
	
	public function deleteMx()
	{
		$array = $this->post('faceId') ?? $this->post('id');
		if (!$this->power(self::page, "interviewDel")) {
			$json['warn'] = L('staffProfiles.tip.permission_evaluate_del_warn');
		} elseif (empty($array)) {
			$json['warn'] = L('staffProfiles.tip.no_data_choose');
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query('talent_pool_interview', " id = '$id' ");
				if ($info['type'] == '评价记录') {
					delete(array('table' => 'talent_pool_interview_detail', 'where' => "orderId = '$id'"));
					$all = find(array('table' => "file", "where" => "targetId = '$id'"));
					foreach ($all['array'] as $val) {
						fileDelete($val['src']);
					}
					//删除附件
					delete(array("table" => 'file', "where" => " targetId = '$id' "));
					//最后删除基本参数
					delete(array("table" => 'talent_pool_interview', "where" => " id = '$id' "));
					//返回
					$warn = L('job.other.delete_success');
					$x++;
				} else {
					$warn = L('staffProfiles.other.del_ev_failed');
				}
				$text .= L('staffProfiles.other.ev_id') . "【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = str_replace(['{{staffName}}'], [$this->control['name']], L('staffProfiles.other.del_ev_text')) . "<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('staffProfiles.other.del_ev_log'));
			$json['warn']     = 2;
		}
		$json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=evaluation&id=" . ($info['talentId'] ?? '');
		return json_encode($json, 320);
	}
	
	/**
	 * 是否拥有超级管理员权限(不可删除一般指超级管理员权限)
	 *
	 * @return bool
	 */
	public static function forceDel()
	{
		$roleArr = (array)json_decode(self::$user['role'], true);
		$all     = find(['table' => 'role', 'where' => "isDel = 1"]);
		foreach ($all['array'] as $role) {
			if (in_array($role['id'], $roleArr)) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 删除员工
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?: $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = L('staffProfiles.tip.permission_del_warn');
		} elseif (empty($array)) {
			$json['warn'] = L('staffProfiles.tip.no_data_choose');
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			
			$force = self::forceDel();
			foreach ($array as $id) {
				$info = query(self::table, " stid = '$id' ");
				$user = query('user', "stid = '$id'");
				if (!$force && $info['workFlow'] == '已复核' && $info['state'] != '离职') {
					$warn = L('staffProfiles.other.staff_del_state_warn');
				} elseif (!$force && $info['workFlow'] == '已复核' && static::total(array('table' => 'examine', 'where' => "node like '%$id%'")) > 0) {
					$warn = L('staffProfiles.other.staff_del_audit_warn');
				} elseif ($user['isDel']) {
					$warn = '此员工为系统不可删除账户';
				} else {
					//操作记录
					delete(array("table" => 'staff_state_record', "where" => " stid = '$id' "));
					//人才库
					delete(array("table" => 'talent_pool', "where" => " id = '$info[talentId]' "));
					//劳务合同
					delete(array("table" => 'staff_contract', "where" => " staffId = '$id' "));
					//劳务合同变更记录
					delete(array("table" => 'staff_contract_change', "where" => " contractId in (select id from staff_contract where staffId = '$id')"));
					//社保记录
					delete(array("table" => 'staff_insure', "where" => " staffId = '$id' "));
					//入职记录
					delete(array("table" => 'staff_entry_record', "where" => " talentId = '$info[talentId]' "));
					//考勤记录
					delete(array('table' => 'work_sign', 'where' => "stid = '$id'"));
					//用户表
					delete(array('table' => 'user', 'where' => "stid = '$id'"));
					//转正记录表
					delete(array('table' => 'staff_formal', 'where' => "staffId = '$id'"));
					//工伤记录表
					delete(array('table' => 'staff_injury', 'where' => "staffId = '$id'"));
					//离职记录表
					delete(array('table' => 'staff_quit_record', 'where' => "staffId = '$id'"));
					//停薪留职表
					delete(array('table' => 'staff_stay_record', 'where' => "staffId = '$id'"));
					//车间考勤员工表
					delete(array('table' => 'workshop_clock_staff', 'where' => "stid = '$id'"));
					//工序报工员工表
					delete(array('table' => 'process_report_staff', 'where' => "stid = '$id'"));
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " stid = '$id' "));
					//返回
					$warn = L('job.other.delete_success');
					$x++;
				}
				$text .= L('staffProfiles.other.staff') . "【{$info['name']}】，ID【" . $info['stid'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = str_replace(['{{staffName}}'], [$this->control['name']], L('staffProfiles.other.staff_del_text')) . "<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('staffProfiles.other.staff_del_log'));
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}
	
	
}
